Python - 如何连接到for循环中的字符串?

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)

  • @André根据您需要的逻辑(对元素进行一些转换?一些不相关的副作用?),将字符串构造从循环中拉出或创建转换后的元素然后应用它来连接它们可能是有意义的。在循环中天真地执行此操作可能对性能“非常”不利(例如,二次减速=添加一个字符串,需要两次相同的字符串;这不是一个好习惯)。 (2认同)

Ada*_*man 6

如果必须,这就是在 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)


Sam*_*ard 5

endstring = ''
for s in list:
    endstring += s
Run Code Online (Sandbox Code Playgroud)

  • 效率低下,使用join()。 (2认同)