Incrementing Strings in Python

81 Views Asked by At

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
2

There are 2 best solutions below

11
C.Nivs On BEST ANSWER

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'
0
SIGHUP On

We can use a direct comparison with 'z' as the question implies that the password must end with a lowercase letter. So it's just:

def increment(password):
    if password:
        if (c := password[-1]) == 'z':
            return password[:-1] + 'a'
        return password[:-1] + chr(ord(c)+1)
    return password