增加 Python 字符串中的最后一位数字

编程入门 行业动态 更新时间:2024-10-14 14:22:23
本文介绍了增加 Python 字符串中的最后一位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在 Python 2.7 中增加用户提供的字符串的最后一位数字.

我可以像这样替换第一个数字:

def increment_hostname(name):尝试:number = re.search(r'\d+', name).group()除了属性错误:返回错误数字 = 整数(数字)+ 1数字 = str(数字)return re.sub(r'\d+', number, name)

我可以用 re.findall 匹配所有数字,然后增加列表中的最后一个数字,但我不知道如何进行替换:

number = re.findall(r'\d+', name)数字 = 数字[-1]数字 = 整数(数字)+ 1数字 = str(数字)

解决方案

使用 否定外观前面看到数字后面没有数字,传递一个函数给re.sub() 替换参数并增加其中的数字:

>>>进口重新>>>s = "foo 123 bar">>>re.sub('\d(?!\d)', lambda x: str(int(x.group(0)) + 1), s)'foo 124 酒吧'

您可能还想以一种特殊的方式处理9,例如,将其替换为0:

>>>def repl(匹配):... 数字 = int(match.group(0))... return str(digit + 1 if digit != 9 else 0)...>>>s = "foo 789 bar">>>re.sub('\d(?!\d)', repl, s)'foo 780 酒吧'

UPD(处理新示例):

>>>进口重新>>>s = "f.bar-29.domain">>>re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s)'f.bar-30.domain'

I'd like to increment the last digit of user provided string in Python 2.7.

I can replace the first digit like this:

def increment_hostname(name): try: number = re.search(r'\d+', name).group() except AttributeError: return False number = int(number) + 1 number = str(number) return re.sub(r'\d+', number, name)

I can match all the digits with re.findall then increment the last digit in the list but I'm not sure how to do the replace:

number = re.findall(r'\d+', name) number = numbers[-1] number = int(number) + 1 number = str(number)

解决方案

Use negative look ahead to see that there are no digits after a digit, pass a function to the re.sub() replacement argument and increment the digit in it:

>>> import re >>> s = "foo 123 bar" >>> re.sub('\d(?!\d)', lambda x: str(int(x.group(0)) + 1), s) 'foo 124 bar'

You may also want to handle 9 in a special way, for example, replace it with 0:

>>> def repl(match): ... digit = int(match.group(0)) ... return str(digit + 1 if digit != 9 else 0) ... >>> s = "foo 789 bar" >>> re.sub('\d(?!\d)', repl, s) 'foo 780 bar'

UPD (handling the new example):

>>> import re >>> s = "f.bar-29.domain" >>> re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s) 'f.bar-30.domain'

更多推荐

增加 Python 字符串中的最后一位数字

本文发布于:2023-11-29 16:05:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646888.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!