0

例えば。「[bezierPath moveToPoint: CGPointMake(7.98, 6.11)];」という文字列があります。2つの浮動小数点数で計算を行い、それらを置き換えたいと思います。

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

最善の方法ではないかもしれませんが、次のようにこれら 2 つの浮動小数点数を取得して、計算を行うことができます。

>>> 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 に答える