[英]Python, context sensitive string substitution
是否可以使用正則表達式在 Python 中做這樣的事情?
將字符串中的每個數字字符加 1
所以輸入“123ab5”會變成“234ab6”
我知道我可以遍歷字符串並手動遞增每個字符(如果它是一個數字),但這似乎不符合 Python 標准。
筆記。 這不是家庭作業。 我已經將我的問題簡化到聽起來像是家庭作業的程度。
a = "123ab5"
b = ''.join(map(lambda x: str(int(x) + 1) if x.isdigit() else x, a))
或者:
b = ''.join(str(int(x) + 1) if x.isdigit() else x for x in a)
或者:
import string
b = a.translate(string.maketrans('0123456789', '1234567890'))
在任何這些情況下:
# b == "234ab6"
編輯-前兩個 map 9
到10
,最后一個將其包裝為0
。 要將前兩個包裝為零,您必須將str(int(x) + 1)
替換為str((int(x) + 1) % 10)
>>> test = '123ab5' >>> def f(x): try: return str(int(x)+1) except ValueError: return x >>> ''.join(map(f,test)) '234ab6'
>>> a = "123ab5"
>>> def foo(n):
... try: n = int(n)+1
... except ValueError: pass
... return str(n)
...
>>> a = ''.join(map(foo, a))
>>> a
'234ab6'
順便說一句,使用簡單的 if 或 try-catch eumiro 解決方案與 join+map 對我來說也是更 Pythonic 的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.