是否可以使用正则表达式在 Python 中执行类似的操作?
Increment every character that is a number in a string by 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"
EDIT - 前两个将 9 映射到 10,最后一个将其包装到 0。要将前两个换成零,您必须将 str(int(x) + 1) 替换为 str((int(x) + 1) % 10)
