Skip to main content
 首页 » 编程设计

python之迭代 str 列表以创建带空格的 str

2025年05月04日10webabcd

我有:

letters = ['h','e','l','l','o'] 

我需要:

'h e l l o' 

所以我试过如下使用 for 循环:

new_str = '' 
for str in letters: 
    new_str += str + ' ' 

然而,结果是:

new_str = 'h e l l o ' 

有没有办法在 o 后面没有空字符串的情况下做到这一点?就像在我已经得到结果之后没有做任何事情一样。

抱歉,我忘了提及是否有一种方法可以通过遍历列表来做到这一点。

请您参考如下方法:

>>> letters = ['h','e','l','l','o'] 
 
>>> mystr = ' '.join(letters) 
 
>>> print mystr 
 
'h e l l o' 

这是最简单、最干净的方法,但是 如果出于某种原因必须使用 for 循环,您可以执行以下操作:

mystr = '' 
# this keeps the whole operation within the for loop 
for i in range(len(letters)): 
    mystr += letters[i] + ' ' 
    if i == len(letters)-1: # this condition will be tested each iteration, but it seemed more in keeping with your question 
        mystr = mystr[:-1]