str()
Turns numbers, lists and any other value into readable text, so you can join it with other strings, print it or save it to a file.
str(object='')
str(object=b'', encoding='utf-8', errors='strict')str() gives you the text form of a value: str(42) is "42", str(3.5) is "3.5", str([1, 2]) is "[1, 2]". It is the same text that print() would show.
You need it when you join numbers to text with +, when you write numbers to a file, or when you want to treat the digits of a number as characters, for example to count them.
str is also the name of the string type itself, so type("hi") == str is True and isinstance(x, str) checks for text. One surprise is how floats look: str(0.1 + 0.2) is "0.30000000000000004", because that is the real value the computer stores. Use an f-string such as f"{x:.2f}" when you want a fixed number of decimals.
Parameters
| Parameter | What it is |
|---|---|
objectoptional, default '' | The value to turn into text. With nothing, str() gives an empty string. |
encodingoptional, default 'utf-8' | Only for bytes: how the bytes were encoded. When given, object must be bytes. |
errorsoptional, default 'strict' | Only for bytes: what to do with bytes that cannot be decoded, e.g. 'replace' or 'ignore'. |
Return value
A new string.
Examples
1Numbers and other values as text
print(str(42))
print(str(3.0))
print(str(True))
print(str(None))
print(str([1, 2, 3]))42 3.0 True None [1, 2, 3]
2Join a number to a message
items = 3
message = "You have " + str(items) + " items in your basket"
print(message)You have 3 items in your basket
An f-string does the same with less typing: f"You have {items} items in your basket".
3Work with the digits of a number
pin = 40712
digits = str(pin)
print(len(digits), "digits")
print("Last two:", digits[-2:])
print("Sum of digits:", sum(int(d) for d in digits))5 digits Last two: 12 Sum of digits: 14
4Floats show their true value
total = 0.1 + 0.2
print(str(total))
print(f"{total:.2f}")0.30000000000000004 0.30
Most decimal fractions cannot be stored exactly in binary. str() shows the stored value; formatting with :.2f shows two decimals.
5Decode bytes into text
data = b"caf\xc3\xa9 au lait"
text = str(data, "utf-8")
print(len(data), len(text))
print(text.upper().encode("ascii", "replace"))13 12 b'CAF? AU LAIT'
Bytes read from a file or the network must be decoded with the right encoding. Without one, str(data) gives the bytes' printed form "b'caf...'", which is rarely what you want.
Common mistakes
Naming a variable str
str = "hello" hides the built-in function, and later str(5) fails because you are now calling a string. Pick another name, such as text.
str = "hello"
try:
print(str(5))
except TypeError:
print("TypeError: a string cannot be called like a function")
del str
print(str(5))TypeError: a string cannot be called like a function 5
Using str() to round
str(2/3) gives all the digits: 0.6666666666666666. For a set number of decimals, format the number instead: f"{2/3:.2f}" gives 0.67.
Questions people ask
How do I convert an int to a string in Python?
str(42) gives "42". Inside a longer message, an f-string is easier: f"Age: {age}".
What is the difference between str() and repr()?
str() is the friendly form for people; repr() is the precise form for programmers. For strings, repr() adds the quotes: str("hi") is hi, repr("hi") is 'hi'.
How do I turn a list into a string without brackets?
Use str.join(): ", ".join(names). For numbers, convert each one: ", ".join(str(n) for n in numbers).
How do I control what str() shows for my own class?
Define a __str__ method that returns the text. print() and str() will both use it.