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

Blender Python字符串处理:如何仅保留浮点数值与逗号分隔符?

在Blender Python中提取字符串中的浮点数值与逗号

方法一:正则表达式(推荐)

直接匹配字符串中的所有浮点数,再用逗号加空格连接,是最精准高效的方式:

import re

# 示例输入字符串
color_str = "<Color (r=0.65, g=0.54, b=0.43)>"
# 匹配所有浮点数(支持正负值,如-0.12)
float_values = re.findall(r'-?\d+\.\d+', color_str)
# 拼接成目标格式
output = ', '.join(float_values)

print(output)  # 输出: 0.65, 0.54, 0.43

如果需要同时匹配整数(比如1或-5)和浮点数,可将正则表达式调整为:

float_values = re.findall(r'-?\d+\.?\d*', color_str)

方法二:字符过滤(备选)

遍历字符串保留允许的字符(数字、小数点、负号、逗号、空格),再清理多余内容:

color_str = "<Color (r=0.65, g=0.54, b=0.43)>"
allowed = set('0123456789.,- ')
# 过滤字符
filtered = ''.join([c for c in color_str if c in allowed])
# 清理首尾空格
output = filtered.strip()

print(output)  # 输出: 0.65, 0.54, 0.43

这种方法适合简单场景,但如果字符串中有无关的标点(比如多余的小数点),可能需要额外清理,不如正则表达式可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:50:39