Python根据模式查找和替换数字

时间:2012-11-20 00:46:08

标签: python parsing

我有一个字符串,我想找到并替换其中的一些数字。即,在那里有多个重复的“v = 324 \ n”,具有不同的值。现在我想将所有这些数字除以n(四舍五入到最接近的整数)并将其保存为新字符串。

目前我正在使用解析包:

n = 10
s = "this is v = 2342\n and another v = 231\n and some stuff..."
for r in findall("v = {:d}\\n", s):
    print r

这给了我结果列表,但我不知道如何更改字符串。 我该怎么办?

1 个答案:

答案 0 :(得分:3)

您可以将一个函数传递给re.sub,该函数采用匹配的模式samples = {:d}\\n(我必须更新)并以某种方式计算它。这是一个演示:

import re

def sampleRounder(match):
    return str(int(float(match.group(1)))) #base=10

s = "this is v = 2342.2\n and another v = 231.003\n and some stuff..."

print(re.sub("v = ([0-9]*\.[0-9]+|[0-9]+)\\n", sampleRounder, s))