Python String和Integer串联[重复]

本文翻译自:Python String and Integer concatenation [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 3 years ago . 3年前关闭。

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,)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值