Skip to content

Instantly share code, notes, and snippets.

@BenMaydan
Last active August 5, 2019 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMaydan/96d46a3b4c6da38d2e6252a95981be7a to your computer and use it in GitHub Desktop.
Save BenMaydan/96d46a3b4c6da38d2e6252a95981be7a to your computer and use it in GitHub Desktop.
Increments a string. For example, aaab would return aaac, abcd would return abce, abzz would return aczz, and zzzz would return zzzz
from string import ascii_lowercase
def increment(string):
"""
Increments a string alphabetically
increment("aabc") would return "aabd"
:param text: Just some plain english text
:return: Incremented string
"""
# Splits the string into a list of lowercase characters
string = list(string.lower())
# Loops over the list of character and when it finds a character that isn't z
# It increments that character a -> b or d -> e
idx = -1
for letter in reversed(string):
if letter != 'z':
string[idx] = ascii_lowercase[ascii_lowercase.index(letter) + 1]
# Stops the loop so it does not increment every letter in the string
break
# Index variable is required because otherwise it would be (1, 2, 3, 4, etc...)
idx -= 1
continue
return ''.join(string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment