在 Python 中用单个空格替换多个空格
我有这个字符串:
mystring = 'Here is some text I wrote '
如何用一个空格替换两个、三个 (...) 空白字符,以便我得到:
mystring = 'Here is some text I wrote'
I have this string:
mystring = 'Here is some text I wrote '
How can I substitute the double, triple (...) whitespace chracters with a single space, so that I get:
mystring = 'Here is some text I wrote'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种简单的可能性(如果您宁愿避免 RE)是
split 和 join 执行您明确询问的任务 - 另外,它们还执行您没有谈论但在示例中看到的额外任务,删除尾随空格;-)。
A simple possibility (if you'd rather avoid REs) is
The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).
正则表达式可用于对组合的空白字符提供更多控制。
匹配 unicode 空白:
仅匹配 ASCII 空白:
有时,仅匹配 ASCII 空白对于保留控制字符(例如 x0b、x0c、x1c、x1d、x1e、x1f)至关重要。
参考:
关于
\s
:关于
re.ASCII
:strip()
将远程删除任何前导和尾随空格。A regular expression can be used to offer more control over the whitespace characters that are combined.
To match unicode whitespace:
To match ASCII whitespace only:
Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.
Reference:
About
\s
:About
re.ASCII
:strip()
will remote any leading and trailing whitespaces.为了完整起见,您还可以使用:
它将快速处理具有相对较少空格的字符串(在这些情况下比
re
更快)。在任何情况下,Alex Martelli 的拆分/合并解决方案的执行速度至少一样快(通常要快得多)。
在您的示例中,使用 timeit.Timer.repeat() 的默认值,我得到以下时间:
编辑:
刚刚发现这篇文章,它对这些方法的速度进行了相当长的比较。
For completeness, you can also use:
which will work quickly on strings with relatively few spaces (faster than
re
in these situations).In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).
In your example, using the default values of timeit.Timer.repeat(), I get the following times:
EDIT:
Just came across this post which provides a rather long comparison of the speeds of these methods.