将版本号更改为个位数的python



我在这样的文件中有一个版本号:

测试 x.x.x.x

所以我像这样抓住它:

import re
def increment(match):
    # convert the four matches to integers
    a,b,c,d = [int(x) for x in match.groups()]
    # return the replacement string
    return f'{a}.{b}.{c}.{d}'
lines = open('file.txt', 'r').readlines()
lines[3] = re.sub(r"b(d+).(d+).(d+).(d+)b", increment, lines[3])

如果最后一个数字是9,我想这样...然后将其更改为 0,然后将前一个数字更改为 1。所以1.1.1.91.1.2.0的改变.

我这样做是:

def increment(match):
    # convert the four matches to integers
    a,b,c,d = [int(x) for x in match.groups()]
    # return the replacement string
    if (d == 9):
        return f'{a}.{b}.{c+1}.{0}'
    elif (c == 9):
        return f'{a}.{b+1}.{0}.{0}'
    elif (b == 9):
        return f'{a+1}.{0}.{0}.{0}'

当其1.1.9.91.9.9.9时出现问题。其中多个数字需要四舍五入。如何处理此问题?

使用整数加法?

def increment(match):
    # convert the four matches to integers
    a,b,c,d = [int(x) for x in match.groups()]
    *a,b,c,d = [int(x) for x in str(a*1000 + b*100 + c*10 + d + 1)]
    a = ''.join(map(str,a)) # fix for 2 digit 'a'
    # return the replacement string
    return f'{a}.{b}.{c}.{d}'

如果您的版本永远不会超过 10,最好将其转换为整数,递增它,然后转换回字符串。这使您可以根据需要使用任意数量的版本号,并且不限于数千个版本号。

def increment(match):
    match = match.replace('.', '')
    match = int(match)
    match += 1
    match = str(match)
    output = '.'.join(match)
    return output

1添加到最后一个元素。如果超过 9 ,请将其设置为 0 并对前一个元素执行相同的操作。根据需要重复:

import re
def increment(match):
    # convert the four matches to integers
    g = [int(x) for x in match.groups()]
    # increment, last one first
    pos = len(g)-1
    g[pos] += 1
    while pos > 0:
        if g[pos] > 9:
            g[pos] = 0
            pos -= 1
            g[pos] += 1
        else:
            break
    # return the replacement string
    return '.'.join(str(x) for x in g)
print (re.sub(r"b(d+).(d+).(d+).(d+)b", increment, '1.8.9.9'))
print (re.sub(r"b(d+).(d+).(d+).(d+)b", increment, '1.9.9.9'))
print (re.sub(r"b(d+).(d+).(d+).(d+)b", increment, '9.9.9.9'))

结果:

1.9.0.0
2.0.0.0
10.0.0.0

最新更新