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

2024-05-31 23:54:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要“连接到for循环中的字符串”。为了解释,我有这个清单:

list = ['first', 'second', 'other']

在for循环中,我需要以这个结束:

endstring = 'firstsecondother'

你能给我一个如何用python实现这一点的线索吗?


Tags: 字符串forlistfirstothersecond线索endstring
3条回答

你不是这样做的。

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'

是你想要的。

如果您在for循环中执行此操作,则效率会很低,因为字符串“addition”连接的伸缩性不好(但这当然是可能的):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
...
>>> s
'firstsecondother'
endstring = ''
for s in list:
    endstring += s

如果必须这样做,可以在for循环中这样做:

mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
  endstring += s

但您应该考虑使用join()

''.join(mylist)

相关问题 更多 >