假設我有字符串testing-1-6-180- 這里我想捕獲第二個數字(無論它是什么),這里是“6”,然后我想將 5 添加到其數值(所以 6),然后輸出string - 所以在這種情況下,結果應該是testing-1-11-180.這是我到目前為止所嘗試的:import remytext = "testing-1-6-180"pat_a = re.compile(r'testing-1-(\d+)')result = pat_a.sub( "testing-1-{}".format( int('\1')+5 ), mytext )...不幸的是,這失敗了:$ python3 test.pyTraceback (most recent call last): File "test.py", line 7, in <module> result = pat_a.sub( "testing-1-{}".format( int('\1')+5 ), mytext )ValueError: invalid literal for int() with base 10: '\x01'那么,如何獲得捕獲的反向引用,以便將其轉換為 int,進行一些算術,然后使用結果替換匹配的子字符串?能夠發布答案就好了,因為弄清楚如何將那里的答案應用到這里的這個問題并不完全是微不足道的,但無論如何沒有人關心,所以我將發布答案作為編輯:import remytext = "testing-1-6-180"pat_a = re.compile(r'testing-1-(\d+)')def numrepl(matchobj): return "testing-1-{}".format( int(matchobj.group(1))+5 )result = pat_a.sub( numrepl, mytext )print(result)結果是testing-1-11-180.
1 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
您可以使用 lambda 來替換:
>>> mytext = "testing-1-6-180"
>>> s = re.sub(r'^(\D*\d+\D+)(\d+)', lambda m: m.group(1) + str(int(m.group(2)) + 5), mytext)
>>> print (s)
'testing-1-11-180'
添加回答
舉報
0/150
提交
取消