-2

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
Ved Panse
  • 1
  • 3

2 Answers2

0

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'
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
  • Downvoter, have any feedback? – C.Nivs Jun 14 '23 at 16:33
  • 2
    Doesn't even get the example right, result should be xza. – Kelly Bundy Jun 14 '23 at 16:33
  • 1
    @KellyBundy *"x should change to y, y to z, z to a"*. Maybe OP's code doesn't reflect the example correctly, but what they typed lines up with the answer provided – C.Nivs Jun 14 '23 at 16:34
  • @KellyBundy is speaking about "xyz should increment to xza" which I believe is just an error on the part of the OP. – JonSG Jun 14 '23 at 16:36
  • 1
    @C.Nivs I believe what they meant was, if they were to increment a string, xyz -> xza -> xzb -> xzc -> ... -> yaa, etc. – Ryan Jun 14 '23 at 16:37
  • 1
    Hi! Thank you so much for your answer. However, can this code be modified in a way such that xyz translates to xza and not yza? Only the last letter needs to be incremented and in case of z, it should change to a while incrementing the second letter. – Ved Panse Jun 14 '23 at 16:37
  • @VedPanse sure, can make that change – C.Nivs Jun 14 '23 at 16:37
  • @VedPanse *last letter* or *last letters*? Can you update your question to more accurately represent your question? – C.Nivs Jun 14 '23 at 16:41
  • @C.Nivs I have updated the question. I have found the answer to my question. Thank you for your help. – Ved Panse Jun 14 '23 at 16:43
  • Do you also think 789+1 is 890? – Kelly Bundy Jun 14 '23 at 16:46
  • @KellyBundy as helpful and uncondescending as that comment is, the issue is that OP didn't flesh out the full use-case. But feel free to post your own answer – C.Nivs Jun 14 '23 at 16:49
0

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
DarkKnight
  • 19,739
  • 3
  • 6
  • 22