在换行符处拆分字符串 [英] Split a string at newline characters
本文介绍了在换行符处拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,比如说
I have a string, say
a = "Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n"
我们如何用分隔符 \n
(换行符)分割上面的内容?
How do we split the above with the delimiter \n
(a newline)?
结果应该是
['Show details1', 'Show details2', ..., 'Show details5']
推荐答案
如果你只关心尾随的换行符,你可以这样做:
If you are concerned only with the trailing newline, you can do:
a.rstrip().split('\n')
参见 str.lstrip() 和 str.strip() 以了解变化.
See, str.lstrip() and str.strip() for variations.
如果您更普遍地担心多余的换行符会产生空项目,您可以这样做:
If you are more generally concerned by superfluous newlines producing empty items, you can do:
filter(None, a.split('\n'))
这篇关于在换行符处拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文