将版本号更改为一位数python

时间:2018-12-28 15:14:43

标签: python arrays regex python-3.x tuples

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

  

测试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.9更改为1.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时发生。需要四舍五入的地方。我该如何处理这个问题?

3 个答案:

答案 0 :(得分:3)

使用整数加法吗?

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}'

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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