You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中将字符串中任意数量空格替换为单个逗号

解决Python3中任意数量空格替换为单个逗号的问题

嘿,这个场景我太熟悉了!直接用字符串的replace(' ', ',')确实只能替换单个空格,碰到多空格就会变成连续的逗号,不过有两个实用的办法能完美解决:

方法一:使用正则表达式(re.sub)

正则可以精准匹配任意数量的空格,然后一次性替换成单个逗号。需要先导入re模块:

import re

# 测试不同空格数量的字符串
test_str1 = "this has white spaces"
test_str2 = "this  has  double  white  spaces"
test_str3 = "this   has   triple   white   spaces"

# 匹配一个或多个空格,替换为单个逗号
# 如果只想匹配空格(不包含制表符、换行等),用 r' +' 而不是 r'\s+'
result1 = re.sub(r'\s+', ',', test_str1)
result2 = re.sub(r'\s+', ',', test_str2)
result3 = re.sub(r'\s+', ',', test_str3)

print(result1)  # 输出: this,has,white,spaces
print(result2)  # 输出: this,has,double,white,spaces
print(result3)  # 输出: this,has,triple,white,spaces

这里的\s+会匹配任意一个或多个空白字符(包括空格、制表符、换行符),如果你的需求只是替换空格,把正则改成r' +'就更精准了。

方法二:用split() + join()(无需额外模块)

Python的字符串split()方法如果不带参数,会自动把任意数量的空白字符作为分隔符,分割后得到没有空字符串的列表,再用逗号把列表元素连接起来就搞定了:

test_str = "this  has  double  white  spaces"

# 分割后用逗号连接
result = ','.join(test_str.split())
print(result)  # 输出: this,has,double,white,spaces

这个方法不需要导入任何模块,代码更简洁,适合只需要处理空白字符(包括空格)的场景。

如果只想处理空格(排除其他空白),可以用列表推导式过滤split(' ')产生的空字符串:

result = ','.join([part for part in test_str.split(' ') if part])

内容的提问来源于stack exchange,提问作者Harry Boy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:58:24