3

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: 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"

As you can see there is a large amount of white space in the middle. How would i remove this using python?

0

5 Answers 5

4

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).

Sign up to request clarification or add additional context in comments.

Comments

1

Where's text is your string:

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

Comments

0

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)

Comments

0

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"

Comments

0

Without using re :

Removing useless spaces :

' '.join(text.split())

Removing useless \n :

'\n'.join(filter(None, text.split('\n')))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.