Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove whitespaces at certain sections of a text in Python?

I have a text which looks like below     

        High     MM Pol Ag to SO Pol Ag

As you can see, there is a whitespace in the beginning, then a word and again some whitespace and then the rest of the text.

What I want is this piece of text MM Pol Ag to SO Pol Ag.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now I can use strip to remove the leading and ending whitespaces like below.

text = text.strip()

High     MM Pol Ag to SO Pol Ag

But the white space after High is varying ie it can sometimes be two spaces or four or maybe more.

How can I get the required text?

Note: The text can vary.

>Solution :

You can split your string to remove spaces, then reconstruct it ignoring the first word:

>>> text = "        High     MM Pol Ag to SO Pol Ag"
>>> " ".join(text.split()[1:])
'MM Pol Ag to SO Pol Ag'

or, using a regex

>>> import re
>>> re.match("^\s*\w*\s*(.*)", text).group(1)
'MM Pol Ag to SO Pol Ag'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading