How To Remove Large Amounts Of White Space From A Python String?
I know there are a few similar questions to mine but I couldn't find a solution for my problem. I have a string which is: 'subject: Exercise Feedback Form persona_id: bresse Q1: Ye
Solution 1:
you could use regular expressions and configure the expression to replace n or more spaces/newline/tabs/blanks by one single space:
import re
s ="hello \n world"print(re.sub("\s{4,}"," ",s))
prints:
hello world
here it will remove all blanks/newlines/tabs/whatever (\s
in regex) if there are at least 4 of them, and will replace only by one space (to avoid that words that were separated are collated after the replacement, you can replace that by a newline or no character).
Solution 2:
Where's text
is your string:
import re
text = re.sub(r"\s{2,}", "", text)
Solution 3:
try this:
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)
Solution 4:
You can use re.sub
:
import re
print(re.sub('(?<=\n)\s+\n', '', content))
Output:
"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"
Solution 5:
Without using re :
Removing useless spaces :
' '.join(text.split())
Removing useless \n :
'\n'.join(filter(None, text.split('\n')))
Post a Comment for "How To Remove Large Amounts Of White Space From A Python String?"