如何在.replace()中使用数字占位符完成指定数组格式替换?
解决"position": [num, num]批量替换为"position": [num, num, 0]的问题
你原来用的text.replace('"position": [%d, %d]', ...)方法行不通,因为str.replace()只能匹配固定字符串,这里的%d会被当成普通字符,根本匹配不到实际的数字内容。要处理这种带变量的匹配替换,得用正则表达式。
具体实现步骤
- 使用Python的
re模块,通过正则匹配任意格式的数字(包括整数、负数、浮点数) - 用捕获组保留原有的两个数字,在替换时追加
, 0
代码示例
处理字符串内容
import re # 示例文本 text = ''' "position": [10, 20] "position": [-3.14, 5.67] "other_key": [1, 2, 3] # 不会被替换 ''' # 正则模式:匹配"position": [数字, 数字]的格式 pattern = r'"position": \[(-?\d+(\.\d+)?), (-?\d+(\.\d+)?)\]' # 替换:保留原数字,添加, 0 processed_text = re.sub(pattern, r'"position": [\1, \3, 0]', text) print(processed_text)
运行后输出:
"position": [10, 20, 0] "position": [-3.14, 5.67, 0] "other_key": [1, 2, 3] # 不会被替换
直接处理文件
如果要批量修改文件内容,可以加上文件读写逻辑:
import re # 读取文件内容 with open("target_file.json", "r", encoding="utf-8") as f: file_content = f.read() # 执行替换 pattern = r'"position": \[(-?\d+(\.\d+)?), (-?\d+(\.\d+)?)\]' new_content = re.sub(pattern, r'"position": [\1, \3, 0]', file_content) # 写入修改后的内容 with open("target_file.json", "w", encoding="utf-8") as f: f.write(new_content)
正则说明
-?:匹配可选的负号(处理负数)\d+:匹配1个或多个数字(整数部分)(\.\d+)?:匹配可选的小数部分(比如.123)\1和\3:对应正则里捕获的第一个和第三个分组,也就是原有的两个数字,确保替换后保留原始数值
内容的提问来源于stack exchange,提问作者LiQ
相关产品推荐
相关产品推荐

