如何删除字符串中的多余空格?

2024-09-30 01:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用API获取数据时,有些值有额外的空格。你知道吗

例如:Z Miramar Wellington Nz

如何纠正?你知道吗


Tags: api空格nzwellingtonmiramar
3条回答
import re

# Using a regular expression, replace any sequence of spaces with a single space
txt = re.sub(' +',' ', txt)

您可以使用^{}

>>> import re
>>> s = 'Z Miramar      Wellington  Nz'
>>> re.sub(r'\s+', ' ', s)
'Z Miramar Wellington Nz'

^{}后跟^{}

>>> ' '.join(s.split())
'Z Miramar Wellington Nz'

把绳子分开,然后再连接起来。像这样的

strText = ' '.join(strText.split())

相关问题 更多 >

    热门问题