Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
Chris Dutrow Avatar asked Apr 27 '11 03:04

Chris Dutrow


People also ask

How will you convert a string to all lowercase in Python?

lower() Return value lower() method returns the lowercase string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string.

How do I remove all white spaces from a string in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do you skip a space in a string in Python?

The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.

How would you convert a string into lowercase?

The toLowerCase() method converts a string to lower case letters.


1 Answers

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
like image 104
John Machin Avatar answered Sep 30 '22 18:09

John Machin