Normally, string concatenation is done in Python using the + operator. However, when working with integers, the + represents addition.
To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.
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.
Modern string formatting:
"{} and {}".format("string", 1)
No string formatting:
>> print 'Foo',0
Foo 0
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.
Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.
s = "string"
i = 0
print (s + repr(i))
The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.
Hope this helps.
Caitlin
format() method can be used to concatenate string and integer
print(s+"{}".format(i))
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}')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With