-3

I'm trying to efficiently add one to the end of a string like this: tt0000001 --> tt0000002 but I'm not sure how to accomplish this.

A complicated way of doing this is to remove the 2 t's at the beginning, count the number of non-zero digits (let's call that number z), make the string an int, add 1, and then create a string with 2 t's, 6 - z 0's, and then the int, but since I need to use many strings (ex: tt0000001, then tt0000002 then tt0000003, etc) many times, it would be great to have a more efficient way of doing this.

Would anyone know how to do this? A one-liner would be ideal if possible.

Thank you!

Jaet
  • 1
  • Someone else had the same problem - so look at https://www.geeksforgeeks.org/python-program-to-increment-suffix-number-in-string/ – jtlz2 May 12 '21 at 14:34
  • 1
    Does this answer your question? [Incrementing the last digit in a Python string](https://stackoverflow.com/questions/23820883/incrementing-the-last-digit-in-a-python-string) – jtlz2 May 12 '21 at 14:35
  • s = `"tt" + str(int(s[2:]) + 1).rjust(7, '0')` where `s ="tt0000001" ` – shahkalpesh May 12 '21 at 14:38

1 Answers1

2

What you describe is essentially correct. It's not as difficult as you suggest, though, as creating a 0-padded string from an integer is supported.

As long as you know that the number is 7 digits, you can do something like

>>> x = 'tt0000001'
>>> x = f'tt{int(x.lstrip("t"))+1:07}'
>>> x
'tt0000002'

Even simpler, though, is to keep just an integer variable, and only (re)construct the label as necessary each time you increment the integer.

>>> x = 1
>>> x += 1
>>> f'tt{x:07}'
'tt0000002'
>>> x += 1
>>> f'tt{x:07}'
'tt0000003'
chepner
  • 497,756
  • 71
  • 530
  • 681