python - 我如何通过在 python 中使用 re.sub 将 "11 12 13 14"转换为 "12 13 14 15"

标签 python regex python-2.7

很容易将 11 12 13 14 转换为 11a 12a 13a 14a,使用:

myStr = "11 12 13 14"
myStr = re.sub(r'(\d*)', r'\1a', myStr)
print myStr # 11a 12a 13a 14a

但是如何使用 re.sub11 12 13 14 转换为 12 13 14 15

最佳答案

使用 re.sub() 的正则表达式解决方案:

import re
string = "11 12 13 14"

def repl(m):
    number = int(m.group(1)) + 1
    return str(number)

print re.sub(r'\b(\d+)\b', repl, string)
# 12 13 14 15

参见 a demo on ideone.com .

正如其他人提到的,这可能不是最合适的解决方案。

关于python - 我如何通过在 python 中使用 re.sub 将 "11 12 13 14"转换为 "12 13 14 15",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38008218/

相关文章:

python - 当我将 PyQt4 中的 QWebView 放入函数中时,它不会打开

python - 为什么这个矩阵初始化给了我意想不到的结果?

python - 如何检查字符串是否包含字母表中的任何字母?

python - 将 float 转换为 int,以便保留所有信息或如何获取长 float 的长度

java - 正则表达式:如果有一个冒号,则添加另一个冒号

python-2.7 - Python 中的动画条形图

JavaScript 正则表达式

javascript - 仍然无法正常工作 - 功能 : letter to next letter(i. e。 a->b) 并将元音大写

python - 枚举类成员显示为已定义类型而不是枚举成员

python - 加密 : AssertionError ("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")