在 python 中增加字符串的最后一位数字
Increment last digits of string in python
我想在 python 中增加从 01 开始的主机名 3. 我找到了一些解决方案,但我在 09 之后遇到了问题。我的代码将它增加到 010。我该如何解决这个问题?
我的代码
re.sub('\d(?!\d)', lambda x: str(int(x.group(0)) + 1), hostname01)
使用 zfill 添加一个 0
像这样:
import re
hostname01 = "hostname10"
print(re.sub('(\d+)', lambda x: str(int(x.group(0)) + 1).zfill(2), hostname01))
您可以匹配数字 1-9 后跟可选数字 0-9 或匹配 09
(?:[1-9]\d*|09)$
import re
hostnames = [
"hostname01", "hostname08", "hostname09", "hostname10", "hostname99", "hostname675"
]
for hostname in hostnames:
print(re.sub('(?:[1-9]\d*|09)$', lambda x: str(int(x.group(0)) + 1), hostname))
输出
hostname02
hostname09
hostname10
hostname11
hostname100
hostname676
我想在 python 中增加从 01 开始的主机名 3. 我找到了一些解决方案,但我在 09 之后遇到了问题。我的代码将它增加到 010。我该如何解决这个问题?
我的代码
re.sub('\d(?!\d)', lambda x: str(int(x.group(0)) + 1), hostname01)
使用 zfill 添加一个 0
像这样:
import re
hostname01 = "hostname10"
print(re.sub('(\d+)', lambda x: str(int(x.group(0)) + 1).zfill(2), hostname01))
您可以匹配数字 1-9 后跟可选数字 0-9 或匹配 09
(?:[1-9]\d*|09)$
import re
hostnames = [
"hostname01", "hostname08", "hostname09", "hostname10", "hostname99", "hostname675"
]
for hostname in hostnames:
print(re.sub('(?:[1-9]\d*|09)$', lambda x: str(int(x.group(0)) + 1), hostname))
输出
hostname02
hostname09
hostname10
hostname11
hostname100
hostname676