简体   繁体   中英

How to combine multiple strings into one Python list?

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', ...]

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).

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']
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM