如何从python字符串中删除大量空格?

我知道有一些与我类似的问题,但我找不到解决我的问题的方法。我有一个字符串,它是:


"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

如您所见,中间有大量空白。我将如何使用 python 删除它?


慕哥9229398
浏览 208回答 4
4回答

炎炎设计

您可以使用正则表达式并将表达式配置为用一个空格替换 n 个或多个空格/换行符/制表符/空格:import res = "hello     \n   world"print(re.sub("\s{4,}"," ",s))印刷:hello world\s如果至少有 4 个空格/换行符/制表符/任何东西(在正则表达式中),它将在这里删除所有空格,并且只替换一个空格(为了避免分隔的单词在替换后被整理,您可以替换那个由换行符或无字符)。

神不在的星期二

text你的字符串在哪里:import retext = re.sub(r"\s{2,}", "", text)

海绵宝宝撒

试试这个:s = """subject: Exercise Feedback Formpersona_id: bresseQ1: YesQ1 comments: Yes everything was found A1Q2: NoQ2 comments: No forgot to email me A2Q3: YesQ3 comments: All was good A3Q4: NoQ4 comments: It was terrible A4Q5_comments: Get Alex to make it better

一只斗牛犬

您可以使用re.sub:import reprint(re.sub('(?<=\n)\s+\n', '', content))输出:"subject: Exercise Feedback Formpersona_id: bresseQ1: YesQ1 comments: Yes everything was found A1Q2: NoQ2 comments: No forgot to email me A2Q3: YesQ3 comments: All was good A3Q4: NoQ4 comments: It was terrible A4Q5_comments: Get Alex to make it bettersubject: Issue With Apppersona_id: bressecomments: Facebook does not work comments feedback"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python