Borislav Hadzhiev
Wed Jun 22 2022·2 min read
Photo by Elia Pellegrini
To concatenate a string and an integer:
str()
class to convert the integer to a string.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.
my_str = 'The number is: ' my_int = 100 # ⛔️ TypeError: can only concatenate str (not "int") to str result = my_str + my_int
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.
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
.
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.
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.
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 {}
.