Home > database >  How to increment string value in Python
How to increment string value in Python

Time:10-06

How to increment strings in Python?

I have the following string: str = 'tt0000002' and I want to increase this string to 'tt0000003', 'tt0000004','tt0000005' (...) to 'tt0010000' using a loop.

How can I do that?

CodePudding user response:

You could directly generate the ids:

example here with values between 2 and 100 with increments of 10:

ids = [f'tt{i:07d}' for i in range(2, 100, 10)]

output:

['tt0000002',
 'tt0000012',
 'tt0000022',
 'tt0000032',
 'tt0000042',
 'tt0000052',
 'tt0000062',
 'tt0000072',
 'tt0000082',
 'tt0000092']

If you really need to increment from your string:

def increment(s):
    # splitting here after 2 characters, but this could use a regex
    # or any other method if the identifier is more complex
    return f'{s[:2]}{int(s[2:]) 1:07d}'

example:

>>> mystr = 'tt0000002'
>>> increment(mystr)
'tt0000003'

edit

here is a "smarter" version that should work with any id of the form 'XXX0000':

def increment(s):
    import re
    try:
        a, b = re.match('(\D*)(\d )', s).groups()
    except (AttributeError, IndexError):
        print('invalid id')
        return 
    return f'{a}{int(b) 1:0{len(b)}d}'

examples:

>>> increment('tt0000002')
'tt0000003'
>>> increment('abc1')
'abc2'
>>> increment('abc999')
'abc1000'
>>> increment('0000001')
'0000002'

CodePudding user response:

#ugly code but works

s='tt0000002'

for k in range(100): #increase the range 
    print(s)
    n=int(s[2:])
    n_s=str(n 1)
    l=len(n_s)

    temp='tt'
    for z in range(0,7-l):
        temp ='0'
        s=temp n_s
  • Related