开发者

Split a string at newline characters

I have a string, say

a = "Show  details1\nShow  details2\nShow  details3\nShow  details4\nShow  d开发者_如何学运维etails5\n"

How do we split the above with the delimiter \n (a newline)?

The result should be

['Show  details1', 'Show  details2', ..., 'Show  details5']


Use a.splitlines(). This will return you a list of the separate lines. To get your "should be" result, add " ".join(a.splitlines()), and to get all in lower case as shown, the whole enchilada looks like " ".join(a.splitlines()).lower().


If you are concerned only with the trailing newline, you can do:

a.rstrip().split('\n')

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


split method:

a.split('\n')[:-1]


 a.split('\n')

would return an empty entry as the last member of the list.so use

a.split('\n')[:-1]


try:

a.split('\n')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜