我需要在循环中“将字符串连接起来”。简单来说,我有这个列表:
list = ['first', 'second', 'other']
在 for 循环内部,我需要以以下方式结束:
endstring = 'firstsecondother'
你能给我一些关于如何在Python中实现这个的线索吗?
我需要在循环中“将字符串连接起来”。简单来说,我有这个列表:
list = ['first', 'second', 'other']
在 for 循环内部,我需要以以下方式结束:
endstring = 'firstsecondother'
你能给我一些关于如何在Python中实现这个的线索吗?
那不是正确的做法。
>>> ''.join(['first', 'second', 'other'])
'firstsecondother'
这就是你想要的。
如果你使用 for
循环来完成,那么效率会比较低,因为字符串“加法”/连接不会很好地扩展(但当然可以实现):
>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
... s += item
...
>>> s
'firstsecondother'
' + '.join(['first', 'second', 'other'])
@史蒂文:' + '.join(['第一', '第二', '其他'])
- Tim Pietzckerendstring = ''
for s in list:
endstring += s
mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
endstring += s
但是您应该考虑使用join()
:
''.join(mylist)
这应该可以工作:
endstring = ''.join(list)
虽然 "".join 更符合 Python 的风格,也是这个问题的正确答案,但确实可以使用 for 循环。
如果这是一项作业任务(如果是,请添加标签!),并且你必须使用 for 循环,那么以下代码可以解决问题(虽然不符合 Python 的风格,如果你是一名专业的 Python 程序员,不应该这样做):
endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
print "This is the word I am adding: " + word
endstring = endstring + word
print "This is the answer I get: " + endstring
你不需要那些'prints',我只是把它们放在那里让你看到正在发生的事情。