TeXaS_pEtE
TeXaS_pEtE

Reputation: 59

Iterating the last numbers in a string by one

I'm looking at how to increment a string in python that has numbers at the end by 1.

For example:

myString = 'test01'

I'd want to iterate the '01' to get '02' (i.e. test02)

How would I deal with a string that has more than one number in it?

myString = 'Test1b01'

I'd only want to iterate the last numbers to get Test1b02

I assume it involves splitting the string but have no idea how to only iterate the last digits.

Upvotes: 1

Views: 196

Answers (3)

slin
slin

Reputation: 411

By your question I assume the number is always the last 2 characters of the string. Then you would separate them and convert them into an integer, increment it, format it so it it always two characters long (so "02" instead of "2") and then add to the part without the number.

def increment(string):
    num = int(string[-2:])
    num += 1
    num = format(num, '02d')
    return string[:-2] + str(num)

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

I suppose you meant "increment" (instead of "iterate").
re.sub solution for extended cases:

import re

myString = 'Test1b01 text test2aa4 '
pat = r'\b(\w+)(\d)\b'
res = re.sub(pat, lambda m: m.group(1) + str(int(m.group(2))+1), myString)
print(res)

The output:

'Test1b02 text test2aa5 '

Regex pattern details:

  • \b - word boundary
  • \w+ - one or more alphanumeric characters
  • \d - one digit (at the end of a word)

Upvotes: 4

Splice, int cast, increment, and turn back to a string is one way such as:

s = 'test12'
# s[:-2] means grab all but the last two characters
# The {:02d} means we want the int shown as two digits
# s[-2:] Means we want the last two characters
new_str = s[:-2] + "{:02d}".format(int(s[-2:]) + 1)
print(new_str)

Output:

test13

Upvotes: 3

Related Questions