社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中删除字符串中的某些空格?[副本]

user10361610 • 5 年前 • 1683 次点击  

我知道有几个类似的问题,但我找不到解决我的问题的方法。 我有一根绳子,它是:

"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删除这个?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39191
 
1683 次点击  
文章 [ 5 ]  |  最新文章 5 年前
Corentin Limier
Reply   •   1 楼
Corentin Limier    6 年前

不使用RE:

删除无用空间:

' '.join(text.split())

正在删除无用的\n:

'\n'.join(filter(None, text.split('\n')))
Ajax1234
Reply   •   2 楼
Ajax1234    6 年前

你可以用 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"
Taohidul Islam
Reply   •   3 楼
Taohidul Islam    6 年前

试试这个:

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)
Jean-François Fabre
Reply   •   4 楼
Jean-François Fabre    6 年前

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

import re

s = "hello     \n   world"
print(re.sub("\s{4,}"," ",s))

印刷品:

hello world

在这里,它将删除所有空格/换行符/制表符/任何内容( \s 在regex中)如果其中至少有4个,并且将仅替换为一个空格(为了避免在替换后对分隔的单词进行排序,可以将其替换为换行符或无字符)。

Hemerson Tacon
Reply   •   5 楼
Hemerson Tacon    6 年前

在哪里? text 您的字符串是:

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