And*_*dré 12 python for-loop concatenation
我需要"连接到for循环中的字符串".为了解释,我有这个清单:
list = ['first', 'second', 'other']
Run Code Online (Sandbox Code Playgroud)
在for循环中我需要以此结束:
endstring = 'firstsecondother'
Run Code Online (Sandbox Code Playgroud)
你能告诉我如何在python中实现这个目标吗?
Tim*_*ker 48
那不是你怎么做的.
>>> ''.join(['first', 'second', 'other'])
'firstsecondother'
Run Code Online (Sandbox Code Playgroud)
是你想要的.
如果你在一个for循环中执行它,它将是低效的,因为字符串"添加"/连接不能很好地扩展(但当然它是可能的):
>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
... s += item
...
>>> s
'firstsecondother'
Run Code Online (Sandbox Code Playgroud)
如果必须,这就是在 for 循环中执行此操作的方法:
mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
endstring += s
Run Code Online (Sandbox Code Playgroud)
但你应该考虑使用join():
''.join(mylist)
Run Code Online (Sandbox Code Playgroud)
endstring = ''
for s in list:
endstring += s
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101424 次 |
| 最近记录: |