2

Python を使用しre.sub()て文字列を文字と一致させ、文字のe直後と最後の桁の後に中かっこを挿入しようとしてeいます。例えば:

12.34e56 to 12.34e{56}
1e10 to 1e{10}

目的の中括弧を挿入するための正しい正規表現が見つからないようです。たとえば、次のように左中かっこを適切に挿入できます。

>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e)')
>>> sub = z = re.sub(pattern, "\1e{", x)
>>> print(sub)
    12.34e{10 # this is the correct placement for the left brace

2 つの後方参照を使用すると、問題が発生します。

>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e).+($)')
>>> sub = z = re.sub(pattern, "\1e{\2}", x)
>>> print(sub)
    12.34e{} # this is not what I want, digits 10 have been removed

誰でも私の問題を指摘できますか? 助けてくれてありがとう。

4

2 に答える 2

7
re.sub(r'e(\d+)', r'e{\1}', '12.34e56')

戻り値'12.34e{56}'

または、同じ結果だが異なるロジック ( に置き換えないeでくださいe):

re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')
于 2011-09-29T11:33:56.797 に答える
1

ブレースの配置が正しくありません。

の前にオプションの小数点以下の桁数があることを保証するソリューションは次のeとおりです。

import re
samples = ['12.34e56','1e10']
for s in samples:
  print re.sub(r'(\d+(?:\.\d+)?)e([0-9]+)',"\g<1>e{\g<2>}",s)

収量:

12.34e{56}
1e{10}
于 2011-09-29T11:43:25.080 に答える