str()

Converts a value to a string.

Returns
A string.
On this page

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

#
Without str() you get an error
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), write f"text {x}".
  • Number of digits in a non-negative integer: len(str(n)).

Related entries

#

Spotted a mistake or missing an example? Write to us.