为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥9229398 2021-06-21 16:07:29
我知道有一些与我类似的问题,但我找不到解决我的问题的方法。我有一个字符串,它是:"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如您所见,中间有大量空白。我将如何使用 python 删除它?
查看完整描述

4 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

您可以使用正则表达式并将表达式配置为用一个空格替换 n 个或多个空格/换行符/制表符/空格:


import re


s = "hello     \n   world"

print(re.sub("\s{4,}"," ",s))

印刷:


hello world

\s如果至少有 4 个空格/换行符/制表符/任何东西(在正则表达式中),它将在这里删除所有空格,并且只替换一个空格(为了避免分隔的单词在替换后被整理,您可以替换那个由换行符或无字符)。


查看完整回答
反对 回复 2021-06-29
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

text你的字符串在哪里:


import re

text = re.sub(r"\s{2,}", "", text)


查看完整回答
反对 回复 2021-06-29
?
海绵宝宝撒

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


查看完整回答
反对 回复 2021-06-29
?
一只斗牛犬

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"


查看完整回答
反对 回复 2021-06-29
  • 4 回答
  • 0 关注
  • 207 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信