Concatenating string and integer in Python

Viewed 498765

In Python say you have

s = "string"
i = 0
print s + i

will give you error, so you write

print s + str(i)

to not get error.

I think this is quite a clumsy way to handle int and string concatenation.

Even Java does not need explicit casting to String to do this sort of concatenation. Is there a better way to do this sort of concatenation, i.e, without explicit casting in Python?

9 Answers

In Python 3.6 and newer, you can format it just like this:

new_string = f'{s} {i}'
print(new_string)

Or just:

print(f'{s} {i}')

The format() method can be used to concatenate a string and an integer:

print(s + "{}".format(i))

Let's assume you want to concatenate a string and an integer in a situation like this:

for i in range(1, 11):
   string = "string" + i

And you are getting a type or concatenation error.

The best way to go about it is to do something like this:

for i in range(1, 11):
   print("string", i)

This will give you concatenated results, like string 1, string 2, string 3, etc.

You can use the an f-string too!

s = "string"
i = 95
print(f"{s}{i}")

If you only want to print, you can do this:

print(s, i)
Related