Python str() Function: Syntax and 6 Examples

If you want to turn any value into text in Python, the Python str function is what you need. It takes a number, list, bytes or object and gives you back a str.

print("Qty: " + str(12))
# Qty: 12

In this tutorial, I’ll explain the syntax, then work through six examples: numbers, order messages, lists, bytes, custom classes and str() vs repr(). Every output comes from Python 3.12.5 in VS Code.

Python str() Syntax

str(object)
str(object, encoding, errors='strict')
str(object, *, errors)
str(*, encoding='utf-8', errors='strict')
ParameterRequiredDefaultDescription
objectNo''Any value to convert
encodingNo'utf-8'Codec for decoding bytes
errorsNo'strict'What to do with bad bytes

Return value: a new str. With no argument, you get an empty string. Otherwise Python calls the object’s __str__(), falling back to repr().

Note: once you pass encoding or errors, the object must be bytes-like. See how to convert bytes to strings in Python.

When to Use str() in Python

  • Joining numbers into a message with +
  • Writing values to a CSV file you open in Excel
  • Decoding bytes from a file or web response
  • Giving your own classes a readable printout

Beginners hit the first one often; read concatenating a string and an int in Python too.

Example 1: Convert a Number to a String with str()

Let me start with numbers, booleans and None:

print(repr(str(42)))
print(repr(str(-3.5)))
print(repr(str(0.1 + 0.2)))
print(repr(str(1e21)))
print(repr(str(True)), repr(str(None)))
print(repr(str()))

Output:

'42'
'-3.5'
'0.30000000000000004'
'1e+21'
'True' 'None'
''
Python str function converting integers, floats, booleans and None to strings in VS Code
repr() shows the quotes.

How does this work? repr() shows the quotes. 0.1 + 0.2 kept every digit, and the big float switched to 1e+21.

More options: converting an integer to a string in Python.

Example 2: Concatenate a String and a Number with str()

Here’s an order line for an Austin, TX store:

order_id = 1047
total = 129.9

print("Order #" + str(order_id) + " total: $" + str(total))
print(f"Order #{order_id} total: ${total:.2f}")

Output:

Order #1047 total: $129.9
Order #1047 total: $129.90
Python str joining an order number and total into a message next to an f-string in VS Code
str() vs an f-string.

How does this work? str(total) printed 129.9. The f-string with :.2f gave $129.90, which customers expect.

Pro Tip: for money, use f-strings with decimal places or comma-formatted numbers.

Example 3: Convert a List or Dictionary to a String in Python

str() works on whole collections too:

cities = ["Austin", "Denver", "Boston"]
stock = {"SKU-101": 12, "SKU-205": 0}
zips = [78701, 80202, 33101]

print(str(cities))
print(str(stock))
print(", ".join(map(str, zips)))

Output:

['Austin', 'Denver', 'Boston']
{'SKU-101': 12, 'SKU-205': 0}
78701, 80202, 33101

How does this work? The list and dict kept their brackets and quotes. For clean text, map(str, ...) converts each ZIP code before the join.

See joining a list of strings into one string and converting a dict to a string.

Example 4: Decode Bytes with the str() encoding Argument

Bytes from a file or API need an encoding:

data = b"Caf\xc3\xa9 Austin"

print(str(data))
print(str(data, "utf-8"))
print(str(data, encoding="ascii", errors="replace"))

Output:

b'Caf\xc3\xa9 Austin'
Café Austin
Caf�� Austin
Python str decoding UTF-8 bytes with the encoding and errors arguments in VS Code
Pass an encoding to decode.

How does this work? Without an encoding, you got the b'...' text. With "utf-8", the é came through.

ASCII can’t read those bytes, so errors="replace" swapped in replacement marks.

Related: the Python bytes() function.

Example 5: Control str() Output with __str__ in a Custom Class

Your own classes decide what str() returns:

class Invoice:
    def __init__(self, number, amount):
        self.number = number
        self.amount = amount

    def __str__(self):
        return f"Invoice {self.number}: ${self.amount:,.2f}"

    def __repr__(self):
        return f"Invoice({self.number!r}, {self.amount})"

inv = Invoice("INV-2026-118", 2450.5)
print(str(inv))
print(repr(inv))
print([inv])

Output:

Invoice INV-2026-118: $2,450.50
Invoice('INV-2026-118', 2450.5)
[Invoice('INV-2026-118', 2450.5)]
Python str calling a custom __str__ method on an Invoice class next to repr in VS Code
__str__ for people, __repr__ for debugging.

How does this work? str(inv) called __str__(). The list used __repr__(), because containers show items with repr().

Also read converting an object to a string in Python.

Example 6: What Is the Difference Between str() and repr()?

Let me show you both on a date and a city name:

from datetime import date

ship = date(2026, 11, 28)
city = "Austin"

print(str(ship), "|", repr(ship))
print(str(city), "|", repr(city))

Output:

2026-11-28 | datetime.date(2026, 11, 28)
Austin | 'Austin'

How does this work? str() gave the friendly 2026-11-28. repr() gave text you could paste back into Python. Use str() for users and repr() for debugging.

For an ASCII-only version of repr(), see the Python ascii() function.

Common Mistakes with Python str()

Here are the Python str() errors I see most:

class Bad:
    def __str__(self):
        return 99

def m1(): return "Total: " + 25
def m2(): return str(5, "utf-8")
def m3(): return str(b"\xff", "utf-8")
def m4(): return str(Bad())

for n, test in enumerate([m1, m2, m3, m4], 1):
    try:
        test()
    except (TypeError, UnicodeDecodeError) as err:
        print(f"{n}. {type(err).__name__}: {err}")

Output:

1. TypeError: can only concatenate str (not "int") to str
2. TypeError: decoding to str: need a bytes-like object, int found
3. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
4. TypeError: __str__ returned non-string (type int)
Common Python str errors: concatenating an int, decoding a non-bytes value, bad UTF-8 and a bad __str__
Four str() errors.
  1. Wrap the number: "Total: " + str(25).
  2. encoding works only on bytes.
  3. Use errors="replace" for messy bytes.
  4. __str__() must return a string.

Mixing bytes and text causes a similar error; see fixing cannot concat str to bytes.

Wrapping Up the Python str() Function

Python’s str() function turns numbers, collections, bytes and objects into text. Add encoding for bytes and __str__() for your classes.

Next, browse more Python built-in functions and methods.

Keep going with these:

What People Ask About Python str() Function

Is str() a function or a class in Python?

It’s a class. Calling str() builds a new string object.

Does str() change the original variable?

No. It returns a new string and leaves the original value as it was.

How do I convert a string back to a number?

Use int("42") or float("19.99"). Non-numeric text raises ValueError.

Is str() faster than an f-string?

They’re close. F-strings read better when you mix text an