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

标签 python string list

我有:

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] 

关于python - 迭代 str 列表以创建带空格的 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20480978/

相关文章:

c++ - 如何打印由另一个字符串链表组成的链表?

python - 无法将输出转换为列表

python - 为 mysql、python 和 django 修改 DYLD_LIBRARY_PATH

string - 将自定义类型转换为字符串

string - Perl 范围字符串 ID

c++ - 带分隔符的getline

java - 检索Java中的内部元素

python - 用于 MIDI 到乐谱(注释)和/或音频翻译的纯 python 库

python - 无法在 Red Hat Linux 上升级 Python

python - 无法仅获取 1 次出现的链接