Home > database >  Increment a String by 1 character in for loop (Python 3)
Increment a String by 1 character in for loop (Python 3)

Time:11-03

Let's say I have an input string str and I want to increase it's value by 1 digit each loop so 'a'->'b' & 'm'->'n', and when it reaches 'z' it increases as shown in the example below.

str= "aaaaa"
output= "aaaab"

str="aaaaz"
output="aaaba"

str ="kbzzz"
output="kcaaa"

I hope you get the idea, it is sort of like a car's odometer. How to implement this function?

CodePudding user response:

A simple approach (using a for-else loop):

def increment(s):
    for i in range(len(s)-1, -1, -1):
        if s[i] != "z":
            break
    else:
        return "a" * (len(s)   1)
    return s[:i]   chr(ord(s[i])   1)   "a" * (len(s) - i - 1)

>>> increment("aaaaa")
'aaaab'
>>> increment("aaaab")
'aaaac'
>>> increment("aazz")
'abaa'
  1. go through the string from the back
  2. stop at the first non-"z"
  3. if no non-"z" is found, return all "a" (increase length)
  4. otherwise increment the non-"z" and reset the suffix to all "a"s

Some documentation:

  • Related