How to concatenate string with integer in Python

In this tutorial, we are going to learn about How to concatenate string with integer in python.

concatenate a string with an integer in Python

In python, concatenation of two strings is easy. It is done by using “+” operator. Let us see an example of concatenating of two strings.

a='hello '
b='world'
print(a+b)

OUTPUT:

hello world

In the above example ‘hello’ and ‘world’ both are strings. so to can concatenate a string with an integer in python easily. But in the case of concatenating string and integer, We cannot use “+” operator directly. If we use it directly we can get TypeError. It shows it can concatenate only two strings not integer values.
To overcome that error we have to do a small change. That is first we want to convert type integer(int) to type string(str). We can convert it by several ways. Here are some examples.

Using str() function:

year=2019
str(year)
type(str)

OUTPUT:

<type 'str'>

str() function uses to convert integer to string. Here str function is used to convert integer 2019 into string. In this way we can convert integer to string. Then the concatenation of two strings is easy. By using + operator we can concatenate a string and an integer.  Here is the coding part which shows  the concatenation of sting and integer.

a='welcome to'
b='2019'
print(a + str(b))

OUTPUT:

welcome to 2019

Using % operator:

We can also concatenate string and integer using “%” operator. This is the process how we can use “%” operator.

a='welcome to'
b='2019'
print("%s %s"%(a,b))

OUTPUT:

welcome to 2019

Here we are using %s operator to print a string. By using %s for a integer it can convert it into a string. By these two methods, we can concatenate string with an integer.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *