python - 删除空格并使 python 字符串中的所有小写

标签 python regex string

如何在 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/

相关文章:

python - Python 中的字符串 + 变量 + 字符串格式化

javascript - 从 facebook graph API 获取全尺寸图片

mysql - REGEXP 不适用于字符名称

.NET Regex 负向后视不起作用

c# - 代码执行是如何进入这个 'if' 语句的?

arrays - 如何从字符串数组中获取文本并将其用作按钮的文本?

python - Pandas 提取多字符正则表达式

python - 使用请求包python时打开的文件太多

python - 如何使用python在azure-data-lake中的文件上应用elasticsearch?

python - 如何在python中创建分组条形图的子图