Python / str() / Convert an Object to a String
Python’s str() returns a readable string representation of an object. Use it to combine numbers with text or keep their textual representation in a variable; it returns a string rather than changing the original object’s type. Decoding bytes and producing JSON require more specific operations.
Basic conversion and the returned type
str(object) returns a str object for values such as numbers and Booleans. Calling str() without an argument returns an empty string. Conversion normally uses the object’s __str__() representation, which a custom class can define. See the official str type reference for the supported forms.
These examples need only Python 3 and its standard library. Save the following complete program as UTF-8 in str_example.py and run python str_example.py in a terminal. Some environments use python3. Each later example is also independent: replace the file contents and run it again.
number = 42
text = str(number)
print(number, type(number).__name__)
print(text, type(text).__name__)
print("ID-" + text)
print(repr(str()))
print(str(None))
Expected output:
42 int
42 str
ID-42
''
None
Both values display as 42, but their types differ. number remains an integer; text is a string. The '' shown with repr() is a zero-length string, whereas str(None) produces the text None, not an empty value.
Conversion is different from numeric formatting
str() produces a number’s basic string representation; it does not specify decimal places or a currency format. Use a formatted string, such as an f-string, when you need a particular display rule.
price = 12.5
print(str(price))
print(f"{price:.2f}")
print("price=" + str(price))
12.5
12.50
price=12.5
12.50 is a string displayed with two decimal places. The original price remains unchanged. Rounding for display and the accuracy of numerical calculations are separate concerns.
Decode bytes to obtain text
bytes stores byte data, while str stores Unicode text. Calling only str(raw) gives the bytes object’s representation. To recover its characters, specify the actual encoding with decode() or str(raw, encoding).
raw = "café".encode("utf-8")
print(str(raw))
print(raw.decode("utf-8"))
print(str(raw, "utf-8"))
b'caf\xc3\xa9'
café
café
The first line’s b prefix and backslash escapes represent bytes. Only the next two lines decode those bytes as UTF-8. Use a different encoding if that is how the file or response was encoded. Setting errors="ignore" merely to suppress errors can silently discard data.
Choose str(), repr(), or JSON for the intended purpose
str() is primarily for readable display; repr() helps inspect an object’s representation during development. Even repr() does not guarantee reconstructible code for every object. For data interchange, use json.dumps() to produce JSON, JavaScript Object Notation, a standard text data format.
import json
data = {"active": True, "count": 0}
print(str(data))
print(json.dumps(data))
print(str("hello\nworld"))
print(repr("hello\nworld"))
{'active': True, 'count': 0}
{"active": true, "count": 0}
hello
world
'hello\nworld'
The dictionary’s str() output uses Python quotes and True, so do not assume it is JSON. A newline in a string creates a real line break when printed through str(); repr() shows an escaped representation such as \n.
Replace only None with an empty string
Use is None if only a missing None value should become empty. An expression such as str(value or "") also converts 0 and False to empty text, losing their meaning.
for value in (None, 0, False):
text = "" if value is None else str(value)
print(repr(text))
''
'0'
'False'
Handle concatenation and decoding failures
Using + directly between a string and a number raises TypeError. Convert the number with str() or use an f-string. If bytes cannot be interpreted with the selected encoding, UnicodeDecodeError is raised; check the original encoding and whether the data is complete.
try:
print("ID-" + 42)
except TypeError:
print("TypeError")
try:
str(b"\xff", "utf-8")
except UnicodeDecodeError:
print("UnicodeDecodeError")
TypeError
UnicodeDecodeError
The final example catches exceptions to show their types. Conversion can also fail when a custom __str__() returns the wrong type or raises an exception internally, so do not assume every failure comes from string concatenation.




