Concatenate a String and an Integer in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Concatenate a String and an Integer in Python #

To concatenate a string and an integer:

  1. Use the str() class to convert the integer to a string.
  2. Use the addition (+) operator to concatenate the two strings.
  3. The result will be the concatenation of the two values.
main.py
my_str = 'The number is: ' my_int = 100 result = my_str + str(my_int) print(result) # 👉 The number is: 100 # ------------------------------ print(f'{my_str}{my_int}') # 👉️ The number is: 100 # ------------------------------ print('{}{}'.format(my_str, my_int)) # 👉️ The number is: 100

The str class takes an object as an argument and returns the str version of the object.

We used the str class to convert the integer to a string because we cannot use the addition operator with an integer and a string.

main.py
my_str = 'The number is: ' my_int = 100 # ⛔️ TypeError: can only concatenate str (not "int") to str result = my_str + my_int
The values on the left-hand and right-hand sides need to be of compatible types, which means we either have to use the str() class to convert the integer to a string, or use the int() class to convert the string to an integer.

An alternative approach is to use a formatted string literal.

Use a formatted string literal to concatenate a string and an integer, e.g. f'{my_str}{my_int}'. By prefixing the string with f we are able to include expressions and evaluate variables by wrapping them in curly braces.

main.py
my_str = 'The number is: ' my_int = 100 result = f'{my_str}{my_int}' print(result) # 👉️ The number is: 100

When using formatted string literals, we don't have to explicitly convert the integer to a string. The conversion is done for us automatically.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_int = 33 result = f'The winner is #{my_int}' print(result) # 👉️ The winner is #33

Make sure to wrap expressions in curly braces - {expression}.

You can also use the str.format() method to concatenate a string and an integer.

main.py
my_str = 'The number is: ' my_int = 100 result = '{}{}'.format(my_str, my_int) # 👉️ The number is: 100 print(result) # 👉️ 'The number is: 100'

The str.format method performs string formatting operations.

main.py
my_int = 30 result = "He is {} years old".format(my_int) print(result) # 👉️ 'He is 30 years old'

The string the method is called on can contain replacement fields specified using curly braces {}.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.