使用正则表达式查找、舍入和替换字符串中的数字

Vas*_*ily 0 python regex python-2.7 python-3.x

我有一个带有多个坐标的字符串,每个坐标都有15(和 16)位精度。该字符串如下所示:

POLYGON ((63.3143749208534741 58.716055226046571,63.406105383130274 58.6706773671378561,63.4052744833828112 58.670392586236112, ...))

我的目标是输出相同的字符串,但坐标四舍五入为严格的13 位精度。

POLYGON ((63.3143749208535 58.7160552260466,63.4061053831303 58.6706773671379,63.4052744833828 58.6703925862361,...

我想可以用正则表达式来完成,但我不明白该怎么做。

熟悉使用python re 模块的人可以解释一下吗?

Avi*_*Raj 5

您可以在 re.sub 中使用 lambda func

>>> s = 'POLYGON ((63.3143749208534741 58.716055226046571,63.406105383130274 58.6706773671378561,63.4052744833828112 58.670392586236112'
>>> re.sub(r'\d+\.\d{13,}', lambda m: format(float(m.group(0)), '.13f'), s)
'POLYGON ((63.3143749208535 58.7160552260466,63.4061053831303 58.6706773671379,63.4052744833828 58.6703925862361'
Run Code Online (Sandbox Code Playgroud)