How to convert a string with some lines to a list that every cell contains one line in Python? -
i have variable string
string type this:
string = """first second third ..."""
i want add every line separate cell of list, because variable size change can't use this:
temp=[] temp.append(s[0:5]) ....
and didn't find helpful function separate lines me.
there built-in function this: str.split
. returns list of string containing whole passed string cut accordingly given character. example:
>>> "foo bar foobar".split(' ') ['foo', 'bar', 'foobar']
here, want use space separator. in case, want have every different line in single string. so, separator new line character, in python represente \n
character. so, have is:
lines_list = s.split('\n')
but, depends on os you're using program: on unix based systems, work. but, windows has chosen use carriage return (\r
in python) and line feed (n
) lines separator. so, if apply previous code on windows system, you'll have list looks ['foo\r', 'bar\r', 'foobar\r']
. problem presence of carriage returns may cause issues, have remove them, doing example this:
lines_list = [line.replace('\r', '') line in lines_list]
basically, line of code create new list (using comprehension list) contains elements of lines_list
, \r
has been replaced by... nothing, has been deleted.
Comments
Post a Comment