11

I want to remove all spaces from a string.

" as fa sdf sdfsdf "

The result would be:

"asfasdfsdfsdf"

There are several ways I can think of to achieve this, and I'm wondering which one is the best.

1.

"".join(" as fa   sdf sdfsdf ".split())

2.

" as fa   sdf sdfsdf ".replace(" ", "")

And I assume that there are more.
Which one is preferred?

4

8 回答 8

6

我相信最好和最有效的方法是第二个版本" as fa sdf sdfsdf ".replace(" ", ""),作为您可以使用该timeit模块的证据:

  • python -m timeit '"".join(" as fa sdf sdfsdf ".split())'

    1000000 loops, best of 3: 0.554 usec per loop

  • python -m timeit '" as fa sdf sdfsdf ".replace(" ", "")'

    1000000 loops, best of 3: 0.405 usec per loop

于 2012-12-02T00:23:36.933 回答
4

replace(" ", "")是最清晰最简洁的。

于 2012-12-02T00:22:33.087 回答
4

使用它来一次删除所有空白:

import re

s = ' as fa   sdf sdfsdf '
s = re.sub(r'\s+', '', s)

s
=> 'asfasdfsdfsdf'

这种方法的优点是它消除了字符之间的所有空格——一个、两个,不管有多少,因为正则表达式r'\s+'匹配“一个或多个”空白字符——包括空格、制表符等。

于 2012-12-02T00:24:10.593 回答
2

使用replace不会删除所有空白字符(例如,换行符、制表符):

>>> 'abc\t\ndef'.replace(" ", "")
'abc\t\ndef'

我更喜欢string.translate

>>> import string
>>> 'abc\t\ndef'.translate(None, string.whitespace)
'abcdef'

编辑:string.translate不适用于 Unicode 字符串;您不妨re.sub('\s', '', 'abc\n\tdef')改用。

于 2012-12-02T00:23:04.657 回答
2

正则表达式

>>> str = "   as fa sdf sdfsdf  "
>>> import re
>>> re.sub(r'\s', '', str)
于 2012-12-02T00:26:45.077 回答
1

re.sub(" ","", s)是我的最爱。

于 2012-12-02T00:23:48.727 回答
1

只是为了混合另一个:

from string import whitespace
ws = set(whitespace)
''.join(ch for ch in my_string if ch not in ws)
于 2012-12-02T01:27:01.083 回答
0

正则表达式很简单并且有效。split()稍微复杂一些。正则表达式优于split().

于 2012-12-02T00:19:28.510 回答