How to convert a string that has newline character

2019-02-21 16:11发布

Possible Duplicate:
split a string in python

I want to change this:

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

to this:

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

I tried some for and while loops and have not been able to do it. I just want the newline character to be removed while triggering to make the next element. I was told to use:

list(str)

which gives

['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']

After this I use .remove() but only one '\n' is removed and the code gets more complicated to spell the colors.

1条回答
倾城 Initia
2楼-- · 2019-02-21 16:49

You want your_str.splitlines(), or possibly just your_str.split('\n')

Using a for loop -- for instructional use only:

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
查看更多
登录 后发表回答