我有一个片段可以找到浮点数,比如1.321234123。我想去掉一些精度,把它变成1.3212。但是我如何访问找到的匹配项,转换它并替换它呢?在
Python源代码:
import fileinput
import re
myfile = open("inputRegex.txt", "r")
for line in myfile:
line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", "foundValue", line.rstrip())
print(line)
输入文件:
^{pr2}$
\1\2
捕获两组括号中的匹配项。这不是四舍五入,但会截断使用^{} ,与
inplace=True
一起使用。打印行将用作每行的替换字符串。在更新
re.sub
可以接受函数作为替换。它将用match对象调用,函数的返回值用作替换字符串。在以下是稍作修改的版本,以使用捕获的组(用于替换功能)。在
^{pr2}$我希望这就是你要找的
相关问题 更多 >
编程相关推荐