Convert an integer to a string in Python

Use str for integer conversion and f-strings for formatted text. Handle concatenation, padding, numeric bases, and conversion back to integers.

Best practices
Python programming and application logging

Use str(number) to get an integer's decimal string representation. When the number belongs inside a larger message, an f-string usually keeps the expression easier to read.

Convert with str()

number = 5
text = str(number)
print(text)        # 5
print(type(text))  # <class 'str'>

The printed characters look the same as the number, but text is a string. str() also supports other objects through their string representation; that does not mean every representation is a number you can parse back.

Embed or format the number

number = 5
message = f"Quantity: {number}"
padded = f"{number:04d}"
print(message)  # Quantity: 5
print(padded)   # 0005

F-strings are available from Python 3.6. They also support format specifications such as zero padding, making them useful beyond a plain type conversion.

Older code often uses str.format(), which remains valid:

text = "{}".format(5)
message = "Quantity: {}".format(5)

Avoid adding a string to an integer

"Quantity: " + 5 raises TypeError. Convert explicitly or use an f-string:

message = "Quantity: " + str(5)
message = f"Quantity: {5}"

These are equivalent ways to construct the message, not arithmetic addition.

FAQ

Do str() and repr() differ for integers? For ordinary built-in integers, they produce the same decimal text. Their broader purposes differ: str() is for readable output, while repr() aims at an informative representation for debugging. For strings, repr() includes quotes and escapes.

Can I convert the result back? int("5") returns 5. Invalid integer syntax raises ValueError; a decimal string such as "5.2" is not accepted by int() directly.

How do I use another base? bin(5), oct(5), and hex(255) return "0b101", "0o5", and "0xff". For digits without the prefix, use a format specification such as format(255, "x"), which returns "ff". Parsing an explicit hexadecimal string uses int("ff", 16).

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting