开发者

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 prototy开发者_JS百科pe like I could in javascript?


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


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

No. Python is not Ruby.


>>> 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'


Here is a solution using regular expression:

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


Here it is:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜