如何将换行作为列表中的单独元素添加?
我在打印一个我应用程序接收到的变量,结果是这样的:
dog
cat
monkey
cow
我想把这个变量添加到一个列表里,像这样:[dog, cat, monkey, cow],但是我不太确定怎么把它变成列表,因为它只是一个字符串变量(所以当我用for item in string:...的时候,我得到的只是每个字母,而不是整个单词)。有没有办法根据每个项目都是新的一行,把它们添加到列表里呢?
2 个回答
2
我觉得你在找的是 str.splitlines
:
>>> mystr = "dog\ncat\nmonkey\ncow"
>>> print(mystr)
dog
cat
monkey
cow
>>> mystr.splitlines()
['dog', 'cat', 'monkey', 'cow']
>>>
来自 文档:
str.splitlines([keepends])
这个方法会把字符串中的每一行分开,返回一个包含这些行的列表。它是通过一种叫做 通用换行符 的方式来分行的。如果你不想要换行符出现在结果列表里,就不需要传入
keepends
,或者把它设为假。如果你想保留换行符,就把keepends
设为真。
2
有一个内置的方法可以用来处理字符串,这个方法叫做 splitlines
。
>>> tst = """dog
cat
monkey
cow"""
>>> tst
'dog\ncat\nmonkey\ncow' # for loop gives you each letter because it's 1 string
>>> tst.splitlines()
['dog', 'cat', 'monkey', 'cow']
当然,你也可以直接把内容添加到它里面:
>>> lst = tst.splitlines()
>>> lst.append("lemur")
>>> lst
['dog', 'cat', 'monkey', 'cow', 'lemur']
想把它变回多行字符串吗?可以使用 join
。
>>> '\n'.join(lst)
'dog\ncat\nmonkey\ncow\nlemur'
>>> print '\n'.join(lst)
dog
cat
monkey
cow
lemur