How do I combine multiple strings into one Python list? I haven't been able to find any Stack Overflow posts addressing this issue.
I created an earlier program that outputted many strings like this:
print(outputted_strings) =
Susan has a cat
Susan has a dog
Susan has a lizard
Susan has a hamster
... (and so on)...
How can I combine this all into one list? like this:
list = ['Susan has a cat', 'Susan has a dog', 'Susan has a lizard', 'Susan has a hamster', ...]
CodePudding user response:
Using splitlines() OR split()
More info about it using splitlines(), using split
outputted_strings = """Susan has a cat
Susan has a dog
Susan has a lizard
Susan has a hamster"""
more_strings = "hello\nthere\nhope\nyou're\ngood"
print(outputted_strings)
print(outputted_strings.splitlines())
print(more_strings)
print(more_strings.split('\n'))
Output:
Susan has a cat
Susan has a dog
Susan has a lizard
Susan has a hamster
['Susan has a cat', 'Susan has a dog', 'Susan has a lizard', 'Susan has a hamster']
hello
there
hope
you're
good
['hello', 'there', 'hope', "you're", 'good']
split()
is more flexible in the way that it lets you choose the criteria to split the strings on (in this case we used \n
new line separator, but it can be anything).
CodePudding user response:
As noted in comments, if you have that chunk of text as a string, you can use splitlines
to get the list you want.
>>> test = """foo
... bar
... baz
... """
>>> test.splitlines()
['foo', 'bar', 'baz']
>>>