删除空格并在字符串中为python制作全部小写

时间:2011-04-27 03:45:09

标签: python regex string

如何从字符串中删除所有空格并在python中将所有字符设为小写?

另外,我可以像在JavaScript中一样将此操作添加到字符串原型中吗?

4 个答案:

答案 0 :(得分:21)

简单的快速答案怎么样?没有map,没有for循环,......

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

答案 1 :(得分:6)

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

没有。 Python不是Ruby。

答案 2 :(得分:2)

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

答案 3 :(得分:2)

以下是使用正则表达式的解决方案:

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

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