Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Python, how can I remove whitespaces from a string?

Posted on 2009-04-27
Medium Priority
Last Modified: 2012-05-06
How can I remove whitespaces from a string (two examples below) so that they just have one whitespace between the words or no whitespaces if applied to the third example?

1. 'The       International Association for Computing'
2. 'From    Qubit'
3. '    Test'

Question by:ScriberUK

Accepted Solution

LunarNRG earned 1200 total points
ID: 24241133
See below for one possible solution, or apply what you learned from the previous question ...


... several of pepr's solutions should work fine here as well.
#!/usr/bin/env python2.5
s1 = 'The       International Association for Computing'
s2 = 'From    Qubit'
s3 = '    Test'
def remove_ws(s):
    return ' '.join(s.split())
print remove_ws(s1)
print remove_ws(s2)
print remove_ws(s3)

Open in new window

LVL 41

Assisted Solution

HonorGod earned 400 total points
ID: 24241214
Something like this perhaps?

>>> import re
>>> s1 = 'The       International Association for Computing'
>>> s2 = 'From    Qubit'
>>> s3 = '    Test'
>>> def blanks( str ) :
...   return re.sub( ' +', ' ', str ).strip()
>>> blanks( s1 )
'The International Association for Computing'
>>> blanks( s2 )
'From Qubit'
>>> blanks( s3 )

Open in new window

LVL 29

Assisted Solution

pepr earned 400 total points
ID: 24241440
When using re, it is better to compile the regular expression in advance. The truth is that regular expressions should be used carefully. The snippet below shows only slightly modified solution of HonorGod. The \s means "whitespace" (also \t, \n). The regular expression is compiled during compilation of the script. The strip() is neccessary if you want to remove the leading and trailing whitespaces. It is not possible to combine removal of leading/trailing spaces in one step with the spaces inside the string.

The LunarNRG solution could also be efficient. The taste matter. If the efficiency is important, you can use the timeit module to measure.

import re
def myReplace(s, repl = ' ', rex = re.compile(r'\s+')):
    return rex.sub(repl, s).strip() 
s1 = 'The       International Association for Computing'
s2 = 'From    Qubit'
s3 = '    Test'
print repr(myReplace(s1))  
print repr(myReplace(s2))  
print repr(myReplace(s3))  

Open in new window


Author Closing Comment

ID: 31574904
Thank you all for your help. I have now read up on join, split and re ;)
LVL 41

Expert Comment

ID: 24252677
Thank you for the assist, and the points.

Good luck & have a great day.

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Suggested Courses
Course of the Month15 days, 2 hours left to enroll

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question