[英]How to remove large amounts of white space from a python string?
我知道有一些類似的問題要解決,但我找不到解決方案。 我有一個字符串是:
"subject: Exercise Feedback Form
persona_id: bresse
Q1: Yes
Q1 comments: Yes everything was found A1
Q2: No
Q2 comments: No forgot to email me A2
Q3: Yes
Q3 comments: All was good A3
Q4: No
Q4 comments: It was terrible A4
Q5_comments: Get Alex to make it better
subject: Issue With App
persona_id: bresse
comments: Facebook does not work comments feedback"
如您所見,中間有大量空白。 我如何使用python刪除它?
text
在哪里是您的字符串:
import re
text = re.sub(r"\s{2,}", "", text)
您可以使用正則表達式並將其配置為用單個空格替換n個或多個空格/換行符/制表符/空白:
import re
s = "hello \n world"
print(re.sub("\s{4,}"," ",s))
印刷品:
hello world
如果至少有四個空格,這里將刪除所有空格/換行符/制表符/(在正則表達式中為\\s
),並且只會替換一個空格(為避免替換后的單詞被整理后再整理,您可以用換行符或無字符替換)。
嘗試這個:
s = """subject: Exercise Feedback Form
persona_id: bresse
Q1: Yes
Q1 comments: Yes everything was found A1
Q2: No
Q2 comments: No forgot to email me A2
Q3: Yes
Q3 comments: All was good A3
Q4: No
Q4 comments: It was terrible A4
Q5_comments: Get Alex to make it better
subject: Issue With App
persona_id: bresse
comments: Facebook does not work comments feedback"""
s = s.replace("\n\n","")
print(s)
您可以使用re.sub
:
import re
print(re.sub('(?<=\n)\s+\n', '', content))
輸出:
"subject: Exercise Feedback Form
persona_id: bresse
Q1: Yes
Q1 comments: Yes everything was found A1
Q2: No
Q2 comments: No forgot to email me A2
Q3: Yes
Q3 comments: All was good A3
Q4: No
Q4 comments: It was terrible A4
Q5_comments: Get Alex to make it better
subject: Issue With App
persona_id: bresse
comments: Facebook does not work comments feedback"
不使用re:
刪除無用的空間:
' '.join(text.split())
刪除無用的\\ n:
'\n'.join(filter(None, text.split('\n')))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.