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?
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.
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.
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.
The toLowerCase() method converts a string to lower case letters.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With