Python String and Integer concatenation [duplicate

2019-01-01 13:00发布

This question already has an answer here:

I want to create string using integer appended to it, in a for loop. Like this:

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

But it returns an error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

What's the best way to concatenate the String and Integer?

9条回答
高级女魔头
2楼-- · 2019-01-01 13:15
for i in range (1,10):
    string="string"+str(i)

To get string0, string1 ..... string10, you could do like

>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']
查看更多
一个人的天荒地老
3楼-- · 2019-01-01 13:19

If we want output like 'string0123456789' then we can use map function and join method of string.

>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'

If we want List of string values then use list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x

USe range() for Python 3.x

查看更多
栀子花@的思念
4楼-- · 2019-01-01 13:31

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use :

string = 'string'
for i in range(11):
    string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+`i` for i in range(11)]

Update as per Python3

You can use :

string = 'string'
for i in range(11):
    string +=str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+str(i) for i in range(11)]
查看更多
登录 后发表回答