Concatenate String And Int In Python

In this post, we will see different ways for how to concatenate string and int in python. So without further ado let’s get started.

Concatenation of string and int means combining both string and int to return the string.

By default, Python does not support the + operation between integers and string. It throws a TypeError.

>>> 5+ 'hello'
ERROR

1. By Using str() function

In this code example, We first convert the integer into the string by using the str() function and then add it to the string.

# Program to Concatenate String And Int In Python
string = "Year is :" # input string
number = 2020 # input number

sentence = string + str(number) # concatenate string and int
print(sentence ) # print result

Here is the output of the above code.

Output :

Output of the program to concatenate string and int in python

2. By Using f-strings

fstrings is the new feature introduced in python 3.6 that allows the developers to embed different expressions inside the string literals, by using minimal possible syntax.

In the following code snippet, We used f-strings to concatenate string and integers.

# using fstring to concatenate string and int
string = "Year is :"
number = 2020 

sentence = f"{string} {number}" # fstring
print(sentence)

3. By Using Format

In the below code, We have used a format method of string to place the string and integer inside it.

string = "Year is :"
number = 2020 

sentence = "{} {}".format(string,number)
print(sentence)

4. By Using % Operator

In the following code, We have used % operator to concatenate them.

string = "Year is :"
number = 2020 

sentence = "%s%s" % (string,number)
print(sentence)

Also read about how to remove character from string in python

Leave a Reply