在 Python 中用单个空格替换多个空格 [英] Substitute multiple whitespace with single whitespace in Python

查看:63
本文介绍了在 Python 中用单个空格替换多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:

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'

推荐答案

一个简单的可能性(如果你宁愿避免 REs)是

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

split 和 join 执行您明确询问的任务——此外,它们还执行您未提及但在您的示例中看到的额外任务,删除尾随空格;-)

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;-).

这篇关于在 Python 中用单个空格替换多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆