簡體   English   中英

Python 字符串按特定字符拆分

[英]Python string splitting by specific characters

我有一個看起來像這樣的字符串:

"\nthis\n \nis\n \nwhat\n \nthe\n \sentence looks\n \n \nlike\n"

有沒有一種簡單的方法來拆分字符串,以便我只得到由 \n 字符串包圍的字符串? 所以結果將是:

['this', 'is', 'what', 'the', 'sentence looks', 'like']

您可以使用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']
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不完全由空格組成,則 append 將其添加到列表中。

對不起,如果我沒有很好地解釋它,我的英語不是很好。

以不同的方式寫了這篇文章,雖然最底層的應該是您可能正在尋找的最佳答案,但您並不清楚您想要什么。

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

你可以使用:

yourString = "\nthis\n \nis\n \nwhat\n \nthe\n \sentence looks\n \n \nlike\n"
yourArray = yourString.split("\n")
print (yourArray)

https://www.w3schools.com/python/ref_string_split.asp

例如:

a = "\nthis\nis\nwhat\nthe\nstring\nlooks\nlike"

那么語法是:

a = a.split("\n")  
a.remove('')  

真的希望它有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM