ZetCode

Python int to string

last modified November 16, 2026 Python 3.15

In this article we show how to convert integers to strings in Python.

Integer to string conversion is a type conversion in which a value of the int type is turned into a value of the str type. Python never does this conversion implicitly; we use the str function, an f-string, the format function, or one of the base conversion functions such as hex. The opposite direction is handled by the int function.

The str function

The built-in str function returns the string version of the given object. For integers, it returns the decimal digits, with a leading minus sign for negative numbers.

str_function.py
n = 42

s = str(n)

print(s)
print(type(n), type(s))
print(len(s))
print(str(-7), str(0), str(1_000_000))

The program converts a few integers to strings and checks the types of the values.

s = str(n)

The str function creates a new string object; the original integer is not changed.

print(str(-7), str(0), str(1_000_000))

Underscores in integer literals only help readability in the source code. They are not part of the value, so str does not output them.

$ python str_function.py
42
<class 'int'> <class 'str'>
2
-7 0 1000000

Python is strongly typed

Python is a dynamically and strongly typed language. Variables do not have declared types, but the values do, and Python does not mix types in operations without an explicit conversion. Weakly typed languages such as Perl or JavaScript convert a number to a string automatically when it is concatenated with a string; Python raises an error.

concat_error.py
n = 3

msg = 'There are ' + n + ' falcons in the sky'
print(msg)

In the example, we try to concatenate strings and an integer with the + operator.

$ python concat_error.py
Traceback (most recent call last):
  File "/home/user/python/concat_error.py", line 3, in <module>
    msg = 'There are ' + n + ' falcons in the sky'
          ~~~~~~~~~~~~~^~~
TypeError: can only concatenate str (not "int") to str

Concatenating with str

To fix the previous program, we convert the integer to a string before the concatenation.

concat_str.py
n = 3

msg = 'There are ' + str(n) + ' falcons in the sky'
print(msg)

We change the integer value of the n variable to a string with the str function. Now all operands of the + operator are strings.

$ python concat_str.py
There are 3 falcons in the sky

Converting with f-strings

An f-string converts each value in its replacement fields to a string, so we do not have to call str ourselves. This is the most common way of putting numbers into text.

fstring_conv.py
n = 3
total = 1250

print(f'There are {n} falcons in the sky')
print(f'Total: {total} items')
print(f'{n} + {total} = {n + total}')

The replacement fields can contain any expression, including arithmetic. The result of n + total is computed as an integer and converted to a string only when the f-string is built.

$ python fstring_conv.py
There are 3 falcons in the sky
Total: 1250 items
3 + 1250 = 1253

Padding and alignment

The format specifier after the colon controls the width and alignment of the converted number. Numbers are aligned to the right by default.

padding.py
n = 42

print(f'[{n:5}]')
print(f'[{n:<5}]')
print(f'[{n:^5}]')
print(f'[{n:05}]')
print(str(n).zfill(5))
print(str(-42).zfill(5))

The program pads the number 42 to five characters in different ways.

print(f'[{n:05}]')

A leading zero in the width pads the number with zeros instead of spaces. The zeros are inserted after the sign, so -42 becomes -0042.

print(str(n).zfill(5))
print(str(-42).zfill(5))

The zfill string method does the same with a string that has already been converted; it is also sign-aware.

$ python padding.py
[   42]
[42   ]
[ 42  ]
[00042]
00042
-0042

Thousands separators and signs

The , and _ options group digits by thousands, and the + option prints the sign for positive numbers too.

grouping.py
n = 1234567890

print(f'{n:,}')
print(f'{n:_}')
print(f'{-n:,}')
print(f'{n:+,}')
print(f'{42:+}', f'{-42:+}')

The grouping options always use a comma or an underscore regardless of the locale. Use the n presentation type together with the locale module for locale-aware separators.

$ python grouping.py
1,234,567,890
1_234_567_890
-1,234,567,890
+1,234,567,890
+42 -42

Binary, octal, and hexadecimal strings

The bin, oct, and hex functions convert an integer to a string in base 2, 8, and 16, with a 0b, 0o, or 0x prefix. The b, o, x, and X presentation types do the same in f-strings, without the prefix unless the # option is given.

bases.py
n = 255

print(bin(n), oct(n), hex(n))
print(f'{n:b} {n:o} {n:x} {n:X}')
print(f'{n:#b} {n:#o} {n:#x}')
print(f'{n:08b}')
print(f'{n:#010b}')
print(f'{0xdeadbeef:_x}')
print(hex(-n))

The program writes the number 255 in several bases.

print(f'{n:08b}')
print(f'{n:#010b}')

Zero padding is often used for bit patterns. With the # option, the width includes the two prefix characters, so we need a width of 10 to get eight binary digits.

print(f'{0xdeadbeef:_x}')

For the binary, octal, and hexadecimal types, the _ option groups digits by four.

print(hex(-n))

Negative numbers get a minus sign before the prefix; Python does not print two's complement representations.

$ python bases.py
0b11111111 0o377 0xff
11111111 377 ff FF
0b11111111 0o377 0xff
11111111
0b11111111
dead_beef
-0xff

The format function and older styles

The built-in format function applies a format specifier to a single value and returns a string. The str.format method and the % operator are older ways of formatting that we still find in existing code.

format_builtin.py
n = 1234567

print(format(n))
print(format(n, ','))
print(format(n, '>12,'))
print(format(n, 'x'))
print('{} items'.format(n))
print('{:,} items'.format(n))
print('%d items' % n)
print('%08d' % n)

The format function uses the same mini-language as f-strings; format(n) without a specifier is equal to str(n). The %d conversion of the % operator converts an integer in decimal; %08d pads it with zeros to eight characters.

$ python format_builtin.py
1234567
1,234,567
   1,234,567
12d687
1234567 items
1,234,567 items
1234567 items
01234567

Joining a list of integers

The str.join method accepts only strings. To join a list of integers, we have to convert each element first.

join_ints.py
vals = [1, 2, 3, 4, 5]

try:
    print(', '.join(vals))
except TypeError as e:
    print('error:', e)

print(', '.join(map(str, vals)))
print(', '.join(str(v) for v in vals))
print(''.join(map(str, vals)))
print(*vals, sep=', ')

Joining integers directly raises a TypeError. The map(str, vals) call applies str to every element; a generator expression does the same. If we only want to print the values, the sep parameter of print converts them for us.

$ python join_ints.py
error: sequence item 0: expected str instance, int found
1, 2, 3, 4, 5
1, 2, 3, 4, 5
12345
1, 2, 3, 4, 5

Booleans are integers

The bool type is a subclass of int. However, str and plain f-string fields give the words True and False, not the digits.

bool_int.py
flag = True

print(isinstance(flag, int))
print(str(flag))
print(f'{flag}')
print(f'{flag:d}')
print(str(int(flag)))
print(f'{flag + 1}')

To get 1 or 0, we either use the d presentation type, which formats the value as an integer, or convert it with int first.

$ python bool_int.py
True
True
True
1
1
2

Digits of a number

Converting a number to a string is a simple way to work with its decimal digits.

digit_list.py
n = 90210

digits = [int(d) for d in str(n)]
print(digits)
print(sum(digits))
print(str(n)[::-1])
print(len(str(n)), len(str(-n)))

We get the list of digits, their sum, the digits in reverse order, and the number of digits. Note that the reversed string keeps the leading zero, which would be lost when converting it back to an integer, and that the minus sign counts as a character.

$ python digit_list.py
[9, 0, 2, 1, 0]
12
01209
5 6

The integer string conversion limit

Converting a very large integer to a decimal string takes quadratic time. Since Python 3.11, the conversion is refused for numbers with more than 4300 digits to prevent denial of service attacks. The limit can be read and changed in the sys module.

digits_limit.py
import sys

n = 10 ** 5000

print(sys.get_int_max_str_digits())

try:
    s = str(n)
except ValueError as e:
    print('error:', e)

sys.set_int_max_str_digits(6000)
s = str(n)
print(len(s), s[:10] + '...')

print(len(hex(n)))

The number 10 ** 5000 has 5001 digits, so str raises a ValueError. After raising the limit with sys.set_int_max_str_digits, the conversion succeeds.

print(len(hex(n)))

The limit applies only to decimal conversions. Bases that are powers of two can be converted in linear time, so hex works for any size. The limit can also be set with the PYTHONINTMAXSTRDIGITS environment variable or the -X int_max_str_digits option.

$ python digits_limit.py
4300
error: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
5001 1000000000...
4155

Converting strings back to integers

The int function converts a string to an integer. It takes an optional base; base 0 means that the base is taken from the prefix of the string, just like in Python literals.

roundtrip.py
n = 255

for s in (str(n), bin(n), oct(n), hex(n)):
    print(s, int(s, 0))

print(int('ff', 16), int('11111111', 2))
print(int(' 1_000 '))

try:
    int('12.5')
except ValueError as e:
    print('error:', e)

Each string produced by str, bin, oct, and hex is converted back with int(s, 0). The int function ignores surrounding whitespace and accepts underscores between digits, but a string with a decimal point is rejected; use int(float(s)) for such strings.

$ python roundtrip.py
255 255
0b11111111 255
0o377 255
0xff 255
255 255
1000
error: invalid literal for int() with base 10: '12.5'

Source

str – Python documentation

Format Specification Mini-Language

Integer string conversion length limitation

In this article we have converted integers to strings in Python. See also Python f-strings and Python data types.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.