0

例如。我有一个字符串:“[bezierPath moveToPoint: CGPointMake(7.98, 6.11)];”。我想对这两个浮点数进行一些计算并替换它们。

4

2 回答 2

2

您可以使用re.sub

>>> import re
>>> def action(matchObj):
...     return str(float(matchObj.group(0)) * 2)
... 
>>> re.sub('\d+\.\d+', action, "[bezierPath moveToPoint: CGPointMake(7.98, 6.11)];")
'[bezierPath moveToPoint: CGPointMake(15.96, 12.22)];'
于 2013-09-01T15:10:48.747 回答
1

可能不是最好的方法,您可以像这样获得这两个浮点数,然后进行计算:

>>> a
'[bezierPath moveToPoint: CGPointMake(7.98, 6.11)];'
>>> x = a.split('(')[1]
>>> x
'7.98, 6.11)];'
>>> y = x.split(')')[0]
>>> y
'7.98, 6.11'
>>> first_no = float(y.split(',')[0])
>>> first_no
7.98
>>> second_no = float(y.split(',')[1])
>>> second_no
6.11
>>> result = first_no - second_no

现在使用以下语法替换字符串:

a.replace('CGPointMake(7.98, 6.11)', str(result))
于 2013-09-01T14:57:09.950 回答