I am trying to change a variable (lett) to the next letter in the alphabet on each iteration of a loop. I have to also be able to set this variable at the beginning of the script to a certain letter (and the initial letter will vary depending on the use of the script). I started with creating the following bit of code:
Initial script (when I was still learning):
while lett_trig == 2:
if set_lett == 2:
lett = "a"
if set_lett == 3:
lett = "b"
if set_lett == 4:
lett = "c"
if set_lett == 5:
lett = "d"
if set_lett == 6:
lett = "e"
if set_lett == 7:
lett = "f"
if set_lett == 8:
lett = "g"
if set_lett == 9:
lett = "h"
#... and this goes on till it reaches if set_let == 27: lett = "z"
set_lett += 1
if set_lett == 28:
set_lett = 2
print lett
# set_lett starts at two because I left set_lett == 1 to create a space (" ")
This is of course a simplification of a larger script.
This is the only simplification I could come up with:
lett_trig = 2
x = 0
a = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
while lett_trig == 2:
lett = a[x]
x += 1
if x == 26:
x = 0
Is there any other way to mathematically change from one letter to another? Through some binary conversion operation? or is the list-way the most efficient?
Answer: after going through all the answers and testing them for efficiency, I found the dict function to be the fastest (and cleanest). An example of the code:
import string
letter_map = dict(zip(string.ascii_lowercase, string.ascii_lowercase[1:] + string.ascii_lowercase[0]))
lett1 = "d"
while ord(lett2) < 122:
print lett1
lett1 = letter_map[lett1]
Use
itertools.cycle:With this,
lettersis an infinite sequence of letters, running from a to z repeatedly. You can use this in awhileloop by callingletters.next()or in aforloop by imposing a termination condition in some fashion, e.g.,itertools.islice.You can put this together into a function:
The
cyclic_lettersfunction also allows the initial letter in the sequence to be selected, defaulting to'a'.Alternatively, you could use a dictionary that shows the next letter for any given letter. You can create a dictionary for that, such as by:
This is just a dictionary, so using, e.g.,
letter_map['c']will produce'd'.In the above,
string.lowercaseis just a string containing the lowercase letters. The value will depend on your locale. If you only want'abcdefghijklmnopqrstuvwxyz', regardless of locale, you can substitutestring.ascii_lowercaseor just give the explicit string.