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.
Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With