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

39,638

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
Share:
39,638

Related videos on Youtube

Israel CA
Author by

Israel CA

Updated on August 08, 2022

Comments

  • Israel CA
    Israel CA almost 2 years

    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.

    • mgibsonbr
      mgibsonbr over 11 years
      str.split('\n')
  • Israel CA
    Israel CA over 11 years
    Thank you very much, it works. I was just wondering if there is a way to do this by using for or while loops?
  • mgilson
    mgilson over 11 years
    @IsraelCA -- Sure there is. But why would you want to?
  • mgilson
    mgilson over 11 years
    @IsraelCA -- Added a for loop solution. I haven't tested it as I'm not at my computer with python at the moment, but I think it should work.
  • Israel CA
    Israel CA over 11 years
    I am trying to teach myself how to do things and I want to see how codes can be written without using python buil in functions but if one can produce their own code to preform those same tasks. Thank you once again for the help.
  • StressedBoi69420
    StressedBoi69420 over 2 years
    .split('\n') worked for me :) Thanks