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

Python-如何连接到for循环中的字符串?,python,for-loop,concatenation,Python,For Loop,Concatenation,我需要“连接到for循环中的字符串”。为了解释,我有以下清单: list = ['first', 'second', 'other'] 在for循环中,我需要以以下内容结束: endstring = 'firstsecondother' 你能告诉我如何在python中实现这一点吗?你不是这样做的 >>> ''.join(['first', 'second', 'other']) 'firstsecondother' 这就是你想要的 如果在for循环中执行,则效率会很低,因

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

list = ['first', 'second', 'other']
在for循环中,我需要以以下内容结束:

endstring = 'firstsecondother'

你能告诉我如何在python中实现这一点吗?

你不是这样做的

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'
这就是你想要的

如果在
for
循环中执行,则效率会很低,因为字符串“加法”/串联不能很好地扩展(当然也有可能):

这应该起作用:

endstring = ''.join(list)
虽然“.join”更像python,并且是这个问题的正确答案,但使用for循环确实是可能的

如果这是一个家庭作业(如果是这样的话,请添加一个标记!),并且您需要使用for循环,那么什么才有效(虽然不是pythonic,如果您是编写python的专业程序员,就不应该这样做):


您不需要“打印”,我只是把它们放在那里,这样您就可以看到发生了什么。

如果您必须这样做,这就是在for循环中执行的方式:

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

但您应该考虑使用<代码> Cube()/代码>:


不要使用
list
作为变量名。一个比较古老但仍然有趣的不同串联技术的比较,我需要在for循环中进行,我需要在for循环中添加一些逻辑。在for循环中可以做到这一点吗?@André根据您需要的逻辑(对元素的一些转换?一些不相关的副作用?),将字符串构造从循环中拉出或创建转换后的元素,然后将其应用于concat是有意义的。在循环中天真地执行此操作可能会对性能非常不利(例如,二次减速=添加一个字符串,需要两倍相同;这不是一个好习惯)。感谢您的回复。这就是我一直在寻找的那段代码。join方法对任何iterable都有效吗?@steven:
'+'。join(['first',second',other'])
嗨,谢谢你的回复。但我真的需要在for循环中完成它。有可能吗?好吧,你可以在循环中的列表中添加字符串,然后加入它们。它比在循环中追加字符串更有效(事实上,这是推荐的方法)。如果效率不高,请使用join()。如果效率不高,请使用join()。
endstring = ''
for s in list:
    endstring += s
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
mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
  endstring += s
''.join(mylist)