Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Python – Concatenate string and int

In Python, we normally perform string concatenation using the + operator. The + operator, however as we know, is also used to add integers or floating-point numbers.

So what would happen if we have a string and an int on both sides of the operand?

Since Python is a dynamically typed language, we would not face any error during compilation, but rather, we get a Runtime Error. (More specifically, a TypeError exception is raised)

The below snippet proves this:

a = "Hello, I am in grade "

b = 12

print(a + b)

Output

Traceback (most recent call last):
  File "concat.py", line 5, in <module>
    print(a + b)
TypeError: can only concatenate str (not "int") to str

So, since we cannot directly concatenate an integer with a string, we need to manipulate the operands so that they can be concatenated. There are multiple ways of doing this.


1. Using str()

We can convert the integer to a string, via the str() function. Now, the new string can now be concatenated with the other string to give the Output;

print(a + str(b))

Output

Hello, I am in grade 12

This is the most common way to convert an integer to a string.

But, we can use other methods as well.

2. Using format()

a = "Hello, I am in grade "

b = 12

print("{}{}".format(a, b))

The output remains the same as before.

3. Using ‘%’ format specifier

a = "Hello, I am in grade "

b = 12

print("%s%s" % (a, b))

While we can specify that both a and b are strings, we can also use C-style format specifiers (%d, %s) to concatenate an integer with a string.

print('%s%d' % (a,b))

The output remains the same for the above code.

4. Using f-strings

We can use Python f-strings on Python 3.6 or above to concatenate an integer with a string.

a = "Hello, I am in grade "

b = 12

print(f"{a}{b}")

5. Printing the string using print()

If we want to directly print the concatenated string, we can use print() to do the concatenation for us.

a = "Hello, I am in grade "
b = 12
print(a, b, sep="")

We join a and b using a null string separator (sep), since the default separator for print() is a space (” “).


Conclusion

In this article, we learned how to concatenate an integer to a string using various methods.

References