Concatenating string and integer in python

2019-01-16 03:26发布

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?

5条回答
我命由我不由天
2楼-- · 2019-01-16 04:01

format() method can be used to concatenate string and integer

print(s+"{}".format(i))
查看更多
女痞
3楼-- · 2019-01-16 04:05

Modern string formatting:

"{} and {}".format("string", 1)
查看更多
虎瘦雄心在
4楼-- · 2019-01-16 04:08

No string formatting:

>> print 'Foo',0
Foo 0
查看更多
forever°为你锁心
5楼-- · 2019-01-16 04:13

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

查看更多
SAY GOODBYE
6楼-- · 2019-01-16 04:23

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.

查看更多
登录 后发表回答