[英]How to combine multiple strings into one Python list?
如何將多個字符串組合成一個 Python 列表? 我找不到任何解決此問題的 Stack Overflow 帖子。
我創建了一個早期的程序,它輸出許多這樣的字符串:
print(outputted_strings) =
Susan has a cat
Susan has a dog
Susan has a lizard
Susan has a hamster
... (and so on)...
我怎樣才能將這一切合並到一個列表中? 像這樣:
list = ['Susan has a cat', 'Susan has a dog', 'Susan has a lizard', 'Susan has a hamster', ...]
使用 splitlines()關於它的更多信息, 使用 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'))
輸出:
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()
在允許您選擇分割字符串的標准方面更加靈活(在這種情況下,我們使用了\n
換行符,但它可以是任何東西)。
如評論中所述,如果您將該文本塊作為字符串,則可以使用splitlines
來獲取所需的列表。
>>> test = """foo
... bar
... baz
... """
>>> test.splitlines()
['foo', 'bar', 'baz']
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.