Last active
April 14, 2018 22:48
-
-
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++)
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
# 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