Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string that has newline characters in it into a list in Python? [duplicate]

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.

like image 249
Israel CA Avatar asked Nov 01 '12 01:11

Israel CA


People also ask

How do you convert a string into a list of characters in Python?

Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function.

How do I convert a string to a list of strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

What does '\ n do in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


1 Answers

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
like image 195
mgilson Avatar answered Oct 15 '22 00:10

mgilson