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
相关产品推荐
相关产品推荐

