解决方法1:使用正则表达式
import re
def remove_extra_spaces(string):
# 使用正则表达式替换超过3个空格的情况
pattern = r'\s{4,}'
return re.sub(pattern, ' ', string)
# 示例用法
text = "这是一个 包含超过3个空格的字符串。"
result = remove_extra_spaces(text)
print(result)
解决方法2:使用字符串的split和join方法
def remove_extra_spaces(string):
# 将字符串按空格分割成列表
words = string.split(' ')
# 过滤掉空的字符串,并只保留前3个空格(即前4个元素)
words = [w for w in words if w != ''][:4]
# 将列表中的元素用空格连接成字符串
return ' '.join(words)
# 示例用法
text = "这是一个 包含超过3个空格的字符串。"
result = remove_extra_spaces(text)
print(result)
这两种方法都可以将超过3个空格的情况替换为一个空格。