我有一個字串如下,
s= 'Mary was born in 3102 in England.'
我想將此字串中的數字反轉為 '2013' 所以輸出將是,
s_output = 'Mary was born in 2013 in England.'
我已經完成了以下操作,但沒有得到我想要的結果。
import re
word = r'\d{4}'
s_output = s.replace(word,word[::-1])
uj5u.com熱心網友回復:
問題是您的“單詞”變數是一個尚未評估的正則運算式。您需要先在“s”字串上對其進行評估,您可以使用 re.search 方法執行此操作,如下所示:
import re
s= 'Mary was born in 3102 in England.'
word = re.search('\d{4}',s).group(0)
s_output = s.replace(word,word[::-1]) #Mary was born in 2013 in Englan
uj5u.com熱心網友回復:
您可以re.sub在此處使用回呼函式:
s = 'Mary was born in 3102 in England.'
output = re.sub(r'\d ', lambda m: m.group()[::-1], s)
print(output) # Mary was born in 2013 in England.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/434522.html
