如何在Python中将包含换行符的字符串转换为列表?

2024-04-29 14:07:39 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
split a string in python

我想改变这个:

str = 'blue\norange\nyellow\npink\nblack'

对此:

list = ['blue','orange', 'yellow', 'pink', 'black']

我试过一些for和while循环,但一直没能做到。我只希望在触发生成下一个元素时删除换行符。我被告知使用:

list(str)

它给予

['b', 'l', 'u', 'e', '\n', 'o', 'r', 'a', 'n', 'g', 'e', '\n', 'y', 'e', 'l', 'l', 'o', 'w', '\n', 'p', 'i', 'n', 'k', '\n', 'b', 'l', 'a', 'c', 'k']

在这之后,我使用.remove(),但只有一个'\n'被删除,代码拼写颜色变得更加复杂。


Tags: instringbluelistsplitorangestryellow
1条回答
网友
1楼 · 发布于 2024-04-29 14:07:39

你想要your_str.splitlines(),或者可能只是your_str.split('\n')

使用for循环——仅用于教学:

out = []
buff = []
for c in your_str:
    if c == '\n':
        out.append(''.join(buff))
        buff = []
    else:
        buff.append(c)
else:
    if buff:
       out.append(''.join(buff))

print out

相关问题 更多 >