This blog post is 16 years old! Most likely, its content is outdated. Especially if it's technical.
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
- Previous:
- Playing with Reverend Bayesian 19 October 2005
- Next:
-
Pandora - a great Internet radio 21 October 2005
- Related by category:
- How much faster is Redis at storing a blob of JSON compared to PostgreSQL? 28 September 2019 Python
- Best practice with retries with requests 19 April 2017 Python
- Fastest way to find out if a file exists in S3 (with boto3) 16 June 2017 Python
- Interesting float/int casting in Python 25 April 2006 Python
- Fastest way to unzip a zip file in Python 31 January 2018 Python
- Related by keyword:
- Python Cookbook arrived 05 April 2005
- Indent text like email clients do 11 November 2004
- PLEAC 31 October 2003
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.
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)