Python String和Integer连接 [英] Python String and Integer concatenation
本文介绍了Python String和Integer连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在for循环中使用附加到它的整数创建字符串。像这样:
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
但它返回错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
连接字符串和整数的最佳方法是什么?
What's the best way to concatenate the String and Integer?
推荐答案
注意:
此答案中使用的方法(反引号)在Python 2的更高版本中已弃用,并在Python 3中删除。使用 str()
代替。
您可以使用:
string = 'string'
for i in range(11):
string +=`i`
print string
它将打印 string012345678910
。
要获得 string0,string1 ... .. string10
您可以使用此作为@YOU建议ed
To get string0, string1 ..... string10
you can use this as @YOU suggested
>>> string = "string"
>>> [string+`i` for i in range(11)]
根据Python3更新
您可以使用:
Update as per Python3
You can use :
string = 'string'
for i in range(11):
string +=str(i)
print string
它将打印 string012345678910
。
要获得 string0,string1 ..... string10
你可以使用它作为@YOU建议
To get string0, string1 ..... string10
you can use this as @YOU suggested
>>> string = "string"
>>> [string+str(i) for i in range(11)]
这篇关于Python String和Integer连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文