Concatenating string and integer in python

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?


Solution 1:

Modern string formatting:

"{} and {}".format("string", 1)

Solution 2:

No string formatting:

>> print 'Foo',0
Foo 0

Solution 3:

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but "still sticking around", %-formatting:

 '%s%d' %(s, i)

In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.