Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading