我有一个看起来像这样的字符串:
"\nthis\n \nis\n \nwhat\n \nthe\n \sentence looks\n \n \nlike\n"
是否有一种简单的方法来分割字符串,以便我只得到被\ n字符串包围的字符串?这样的结果将是:
['this', 'is', 'what', 'the', 'sentence looks', 'like']
答案 0 :(得分:1)
您可以使用re.split()
>>> import re
>>> s = "\nthis\n \nis\n \nwhat\n \nthe\n \nsentence looks\n \n \nlike\n"
>>> re.split(r'\n\s+', s.strip())
['this', 'is', 'what', 'the', 'sentence looks', 'like']
答案 1 :(得分:1)
s = "\nthis\n \nis\n \nwhat\n \nthe\n \nsentence looks\n \n \nlike\n"
print([x for x in s.strip().split('\n') if x.replace(' ', '')])
我在这里使用列表理解。 x 迭代由换行符("\n"
)分隔的字符串,如果 x 并非完全由空格组成,请将其附加到列表中。
很抱歉,如果我不能很好地解释它,我的英语不是很好。
答案 2 :(得分:0)
尽管您最想要的答案应该是最底下的答案,但是用不同的方式编写的内容并不清楚您想要的内容。
#--- Original code here
text = "\nthis\n \nis\n \nwhat\n \nthe\n \nsentence looks\n \n \nlike\n"
print(text)
print('Original')
#--- Modified code 1
text = ['this', 'is', 'what', 'the', 'sentence', 'looks', 'like']
print(text)
print('mod 1')
#--- Modified code 2
text = """this is what the sentence looks like"""
print(text)
print('mod 2')
#--- Modified code 3
text = "\nthis\n \nis\n \nwhat\n \nthe\n \nsentence looks\n \n \nlike\n".replace('\n', '')
print(text.split('\n'))
print('mod 3')
答案 3 :(得分:-1)
您可以使用:
yourString = "\nthis\n \nis\n \nwhat\n \nthe\n \sentence looks\n \n \nlike\n"
yourArray = yourString.split("\n")
print (yourArray)
答案 4 :(得分:-1)
例如:
a = "\nthis\nis\nwhat\nthe\nstring\nlooks\nlike"
那么语法是:
a = a.split("\n")
a.remove('')
真的希望对您有帮助