str()
Python · Variables & Data Types
Theory
str() returns a text version of any value. Python asks the object for its readable string form (its __str__ method), so numbers, booleans, None, lists and dicts all work: str(25) is '25', str(None) is 'None' and str([1, 2]) is '[1, 2]'. The original value is untouched; you get a brand-new string object.
The most common reason you need it is that + between a string and a number is a TypeError: 'Age: ' + 25 fails because Python refuses to guess whether you meant math or text. 'Age: ' + str(25) works. A related function, repr(), returns the developer-facing form that includes quotes for strings, which is what you see when a list is printed. In modern code, f-strings like f'Age: {age}' call str() for you and are usually cleaner than manual conversion.
Why we use it
Programs constantly turn values into text for messages, file names, log lines and reports. str() is the explicit, safe way to make that conversion and fix the classic 'can only concatenate str (not "int") to str' error.
When to use it
Use str() when joining a number into a string with + or when a function needs text, such as writing to a file. When building whole sentences, an f-string is usually more readable. Use repr() when debugging, to see quotes and hidden characters.
How it works
- str(value) is called
- Python calls the object's __str__ method
- Does the type define a custom __str__? Yes: Use that readable text. No: Fall back to repr(), the developer form.
- Create a new str object; the original value is unchanged
- e.g. 'Age: ' + str(25) gives 'Age: 25'
Syntax
str(value)Example
age = 25
message = "Age: " + str(age)
print(message)Key points
- Needed before concatenating a number to a string with +
- Works on virtually any type: numbers, booleans, None, lists, dicts
- Returns a new string; the original value is not changed
- f-strings call str() for you: f'Age: {age}'
- repr() shows the developer view, e.g. repr('hi') includes the quotes