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

如何使用Python将数字字母混合的字符串拆分为独立词组?

回答

有没有直接可用的内置函数?

Python没有专门实现该自定义拆分逻辑的内置函数。该需求的核心是按「数字开头+后续非数字内容」的规则切割字符串,属于自定义模式匹配场景,你可以用Python标准库中的re(正则表达式)模块实现,无需安装第三方依赖。

具体实现代码

import re

origin_str = "3quartos2suítes3banheiros126m²"
# 匹配所有【数字组 + 非数字组】的组合
match_groups = re.findall(r'(\d+)(\D+)', origin_str)

result = []
for num, content in match_groups:
    # 面积单位m²和数字之间不加空格,其余内容加空格分隔
    if content.startswith('m²'):
        result.append(f"{num}{content}")
    else:
        result.append(f"{num} {content}")

# 每个条目之间间隔两个换行,匹配要求的空行格式
output = '\n\n'.join(result)
print(output)

输出验证

运行代码后输出和要求的格式完全一致:

3 quartos

2 suítes

3 banheiros

126m²

内容的提问来源于stack exchange,提问作者Guilherme Celli Fadel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:39:00