URL: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442460

I've just uploaded my second Python Cookbook recipe. It's unfortunately not rocket science but it's application is potentially very useful. With this little function you can generate the next number in a string that contains at least one number.

The mini unittest is quite interesting perhaps:


$ python increment_strings.py
from 10dsc_0010.jpg to 10dsc_0011.jpg
from dsc_9.jpg to dsc_10.jpg
from 0000001.exe to 0000002.exe
from ref-04851 to ref-04852

Comments

oneliner

Looks to big for me... this will also work

import re
def increment(s):
....re.sub(r'\d+(?=[^\d]*$)', lambda m: str(int(m.group())+1).zfill(len(m.group())), s)

It's also faster. If you think it's too complex you can break it up.

oneliner

slightly more readable version:

last_number = re.compile(r'\d+(?=[^\d]*$)')

def increment(string):
....def increment_number(match):
........num_str = match.group(1)
........str( int(num_str) + 1).zfill( len(num_str) )

....return last_number.sub(increment_number, string)

Your email will never ever be published.

Previous:
Playing with Reverend Bayesian October 19, 2005 Python
Next:
Pandora - a great Internet radio October 21, 2005 Music
Related by category:
How I run standalone Python in 2025 January 14, 2025 Python
get in JavaScript is the same as property in Python February 13, 2025 Python
How to resolve a git conflict in poetry.lock February 7, 2020 Python
Best practice with retries with requests April 19, 2017 Python
Related by keyword:
Spot the JavaScript bug with recursion and incrementing September 28, 2022 JavaScript
PLEAC October 31, 2003 Misc. links
Python Cookbook arrived April 5, 2005 Books
Indent text like email clients do November 11, 2004 Python