Skip to content

Instantly share code, notes, and snippets.

@jlp78
Last active April 14, 2018 22:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlp78/f306afc919dc06c8ce156475fc9320bf to your computer and use it in GitHub Desktop.
Save jlp78/f306afc919dc06c8ce156475fc9320bf to your computer and use it in GitHub Desktop.
increment a string (i.e. "A" => "B", "Z" => "AA", "AA" => "AB", etc.) in Python (in Perl, assuming "A" is in $s, it's $s++)
# lifted from http://bit.ly/2iJfRou (codereview.stackexchange.com)
# yeah, I can't believe how painful this is in Python. Perl's auto-incrementing
# strings have this beat by a mile.
def incr_chr(c):
return chr(ord(c) + 1) if c != 'Z' else 'A'
def incr_str(s):
lpart = s.rstrip('Z')
num_replacements = len(s) - len(lpart)
new_s = lpart[:-1] + incr_chr(lpart[-1]) if lpart else 'A'
new_s += 'A' * num_replacements
return new_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment