为了账号安全,请及时绑定邮箱和手机立即绑定

将版本号更改为个位数python

将版本号更改为个位数python

PIPIONE 2021-09-28 13:30:29
我在这样的文件中有一个版本号:测试 xxxx所以我像这样抓住它:import redef 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.9更改为1。因此更改为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.9或时出现问题1.9.9.9。多个数字需要四舍五入的地方。我该如何处理这个问题?
查看完整描述

3 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

使用整数加法?


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


查看完整回答
反对 回复 2021-09-28
?
九州编程

TA贡献1785条经验 获得超4个赞

如果您的版本永远不会超过 10,最好将其转换为整数,将其递增,然后再转换回字符串。这允许您根据需要增加尽可能多的版本号,并且不限于数千个。


def increment(match):

    match = match.replace('.', '')

    match = int(match)

    match += 1

    match = str(match)

    output = '.'.join(match)

    return output


查看完整回答
反对 回复 2021-09-28
?
湖上湖

TA贡献2003条经验 获得超2个赞

添加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


查看完整回答
反对 回复 2021-09-28
  • 3 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信