Home > database >  Is there a difference between str() function and class str in Python
Is there a difference between str() function and class str in Python

Time:01-29

The Python Language Reference 3.11.1 mentions a str() function as:

Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function).

How is this different from the class str? Or, when I write

str()

What is called? The function or the class?

CodePudding user response:

Check the output of help(str):

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. [...]
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).

So, in short: str(obj) calls the constructor of the str class. What you refer to as the str function is exactly that: the class' constructor.

CodePudding user response:

In Python, str is both a built-in class and a built-in function. The class str represents a string object, and it has various methods such as upper(), replace(), etc. that can be called on string objects.

On the other hand, the str() function is used to convert an object to a string. For example, you can use str(123) to convert the integer 123 to the string "123". The str() function will call the __str__ method of the object, which should return a string representation of the object.

So when you write str() in your code, it will call the built-in str() function, which converts the passed object to a string by calling the __str__ method of the object.

CodePudding user response:

Yes, there is a difference between the str() function and the str class in Python.

str() is a built-in function in Python that converts a specified object to a string. It can convert numbers, lists, tuples, and other objects to strings.

str is a built-in class in Python that represents strings. A string is an object of the str class and can be created by enclosing a sequence of characters in quotes.

So in summary, str() is a function, which converts any data type to string. And str is a class which creates the object of string.

  • Related