本文翻译自:Python String and Integer concatenation [duplicate]
I want to create string using integer appended to it, in a for loop. 我想在for循环中使用附加到整数的字符串来创建字符串。 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? 连接字符串和整数的最佳方法是什么?
#1楼
参考:https://stackoom.com/question/Bwja/Python-String和Integer串联-重复
#2楼
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. 在更高版本的Python 2中不建议使用此答案中的方法(反引号),在Python 3中将其删除。请改用str()
函数。
You can use : 您可以使用 :
string = 'string'
for i in range(11):
string +=`i`
print string
It will print string012345678910
. 它将打印string012345678910
。
To get string0, string1 ..... string10
you can use this as @YOU suggested 要获取string0, string1 ..... string10
,可以将其用作@YOU建议
>>> string = "string"
>>> [string+`i` for i in range(11)]
Update as per Python3 按照Python3更新
You can use : 您可以使用 :
string = 'string'
for i in range(11):
string +=str(i)
print string
It will print string012345678910
. 它将打印string012345678910
。
To get string0, string1 ..... string10
you can use this as @YOU suggested 要获取string0, string1 ..... string10
,可以将其用作@YOU建议
>>> string = "string"
>>> [string+str(i) for i in range(11)]
#3楼
If we want output like 'string0123456789'
then we can use map function
and join
method of string. 如果我们想要像'string0123456789'
这样'string0123456789'
输出,那么我们可以使用map function
和string的join
方法。
>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'
If we want List of string values then use list comprehension
method. 如果我们要使用字符串值列表,请使用list comprehension
方法。
>>> ['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 对Python 2.x使用xrange()
USe range()
for Python 3.x 适用于Python 3.x的range()
#4楼
for i in range (1,10):
string="string"+str(i)
To get string0, string1 ..... string10
, you could do like 要获取string0, string1 ..... string10
,您可以这样做
>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']
#5楼
for i in range[1,10]:
string = "string" + str(i)
The str(i)
function converts the integer into a string. str(i)
函数将整数转换为字符串。
#6楼
string = 'string%d' % (i,)