Search code examples
pythonstringfunctionincrementletter

Incrementing Strings in Python


How do I increment strings in python? For example, x should change to y, y to z, z to a. Please note that only the last letter should change. For example, the word Ved should change to Vee, and not Wfe

Other examples: xyz should increment to xza.

def increment(password):
    char = password[-1]

    i = ord(char[0])

    i += 1

    if char == 'z':
        return password[:-2] + increment(password[-2]) + 'a'
    char = chr(i)

    return password[:-1] + char

Solution

  • This is basically a cesar cipher, and can be implemented using the str.translate method:

    from string import ascii_lowercase as letters
    
    # build your map of all lowercase letters
    # to be offset by 1
    m = str.maketrans(dict(zip(letters, (letters[1:] + 'a'))))
    
    # split your string
    s = 'xyz'
    first, last = s[0], s[1:]
    
    # make the translation using your prebuilt map
    newlast = last.translate(m)
    
    print(''.join((first, newlast)))
    
    'xza'