如何在 python 中删除字符串中的所有空格并使所有字符小写?
此外,我可以像在 javascript 中那样将此操作添加到字符串原型(prototype)吗?
最佳答案
简单的快速回答怎么样?没有 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
关于python - 删除空格并使 python 字符串中的所有小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5799090/