How to convert a string that has newline character

2019-02-21 16:41发布

问题:

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:

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