Chris Dutrow
Chris Dutrow

Reputation: 50372

Remove whitespace and make all lowercase in a string for python

How do I remove all whitespace from a string and make all characters lowercase in python?

Also, can I add this operation to the string prototype like I could in javascript?

Upvotes: 11

Views: 24725

Answers (5)

Medhat Fawzy
Medhat Fawzy

Reputation: 78

Here it is:

your_string.replace(" ","").lower()

Upvotes: 2

John Machin
John Machin

Reputation: 82992

How about an uncomplicated fast answer? No map, no for loops, ...

>>> s = "Foo Bar " * 5
>>> s
'Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar '
>>> ''.join(s.split()).lower()
'foobarfoobarfoobarfoobarfoobar'
>>>

[Python 2.7.1]

>python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(c.lower() for c in s if not c.isspace())"
100000 loops, best of 3: 11.7 usec per loop

>python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(  i.lower() for i  in s.split()  )"
100000 loops, best of 3: 3.11 usec per loop

>python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join( map(str.lower, s.split() )  )"
100000 loops, best of 3: 2.43 usec per loop

>\python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(s.split()).lower()"
1000000 loops, best of 3: 1 usec per loop

Upvotes: 35

sateesh
sateesh

Reputation: 28693

Here is a solution using regular expression:

>>> import re
>>> test = """AB    cd KLM
    RST l
    K"""
 >>> re.sub('\s+','',test).lower()
  'abcdklmrstlk'

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342649

>>> string=""" a b      c
... D E         F
...                     g
... """
>>> ''.join(  i.lower() for i  in string.split()  )
'abcdefg'
>>>

OR

>>> ''.join( map(str.lower, string.split() )  )
'abcdefg'

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

''.join(c.lower() for c in s if not c.isspace())

No. Python is not Ruby.

Upvotes: 9

Related Questions