Last active
August 5, 2019 22:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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