4 回答
TA贡献1808条经验 获得超4个赞
您可以使用正则表达式并将表达式配置为用一个空格替换 n 个或多个空格/换行符/制表符/空格:
import re
s = "hello \n world"
print(re.sub("\s{4,}"," ",s))
印刷:
hello world
\s如果至少有 4 个空格/换行符/制表符/任何东西(在正则表达式中),它将在这里删除所有空格,并且只替换一个空格(为了避免分隔的单词在替换后被整理,您可以替换那个由换行符或无字符)。
TA贡献1809条经验 获得超8个赞
试试这个:
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
TA贡献1784条经验 获得超2个赞
您可以使用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"
添加回答
举报