2024-05-31 23:54:46 发布
网友
我需要“连接到for循环中的字符串”。为了解释,我有这个清单:
list = ['first', 'second', 'other']
在for循环中,我需要以这个结束:
endstring = 'firstsecondother'
你能给我一个如何用python实现这一点的线索吗?
你不是这样做的。
>>> ''.join(['first', 'second', 'other']) 'firstsecondother'
是你想要的。
如果您在for循环中执行此操作,则效率会很低,因为字符串“addition”连接的伸缩性不好(但这当然是可能的):
for
>>> 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()
''.join(mylist)
你不是这样做的。
是你想要的。
如果您在
for
循环中执行此操作,则效率会很低,因为字符串“addition”连接的伸缩性不好(但这当然是可能的):如果必须这样做,可以在for循环中这样做:
但您应该考虑使用
join()
:相关问题 更多 >
编程相关推荐