PythonBuilt-in functions
str()
Converts a value to a string.
- Returns
- A string.
Example
#Python
points = 120
print("You have " + str(points) + " points")
print(str([1, 2, 3]))
print(str(None), str(True))
print(len(str(12345)))Resultsaved result, you can check it
You have 120 points
[1, 2, 3]
None True
5
Definition and usage
#The str() function creates a text representation of any value. The number 42 becomes the string "42", a list becomes the string "[1, 2]", and None becomes the string "None".
It comes in handy when combining text with numbers using +, because Python doesn't join strings and numbers automatically. In practice, f-strings are more convenient, since they convert values on their own.
For your own classes, the result of str() depends on the __str__ method. Defining it makes your objects look good inside print().
Syntax
#Syntax
str(object)Parameters
#object
any value
The value to convert to text.
More examples
#Python
try:
print("Level: " + 7)
except TypeError as error:
print(error)Resultsaved result, you can check it
can only concatenate str (not "int") to str
Good practices
#- Instead of
"text " + str(x), writef"text {x}". - Number of digits in a non-negative integer:
len(str(n)).
Related entries
#- f-stringsStrings with inserted expression values: f"You have {points} pts".
- int()Converts a value to an integer.
- print()Writes values to standard output, which is the console by default.
- str.format()Inserts values into the places marked with curly braces.
- __str__() and __repr__()Methods that define an object’s text appearance: readable for the user (__str__) and technical for the programmer (__repr__).
Spotted a mistake or missing an example? Write to us.