How to add new line as a separate element on a list?

Question:

I’m printing a variable my app is receiving and I get something like:

dog
cat
monkey
cow

I want to add this to a list as [dog,cat,monkey,cow] but I’m unsure how to get this as a list as its just all in a string variable (so when I do a for item in string:…I just get each letter separately and not the word). Is there a way to add each item to a list based on the fact that each item is a new line?

Asked By: Lostsoul

||

Answers:

There’s a built-in method of strings for this exact purpose called splitlines.

>>> tst = """dog
cat
monkey
cow"""
>>> tst
'dogncatnmonkeyncow'   # for loop gives you each letter because it's 1 string
>>> tst.splitlines()
['dog', 'cat', 'monkey', 'cow']

Now of course you can just append to it:

>>> lst = tst.splitlines()
>>> lst.append("lemur")
>>> lst
['dog', 'cat', 'monkey', 'cow', 'lemur']

Want it back as a multi-line string? Use join.

>>> 'n'.join(lst)
'dogncatnmonkeyncownlemur'
>>> print 'n'.join(lst)
dog
cat
monkey
cow
lemur
Answered By: 2rs2ts

I believe you are looking for str.splitlines:

>>> mystr = "dogncatnmonkeyncow"
>>> print(mystr)
dog
cat
monkey
cow
>>> mystr.splitlines()
['dog', 'cat', 'monkey', 'cow']
>>>

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to
splitting lines. Line breaks are not included in the resulting list
unless keepends is given and true.

Answered By: user2555451
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.