Gronk
Gronk

Reputation: 391

How to create a letter progression for a variable in a loop in Python?

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]

Upvotes: 1

Views: 1751

Answers (5)

Michael J. Barber
Michael J. Barber

Reputation: 25042

Use itertools.cycle:

import itertools
import string
letters = itertools.cycle(string.lowercase)

With this, letters is an infinite sequence of letters, running from a to z repeatedly. You can use this in a while loop by calling letters.next() or in a for loop by imposing a termination condition in some fashion, e.g., itertools.islice.

You can put this together into a function:

def cyclic_letters(start='a'):
    i = string.lowercase.index(start)
    letts = string.lowercase[i:] + string.lowercase[:i]
    return itertools.cycle(letts)

The cyclic_letters function 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:

letter_map = dict(zip(string.lowercase, string.lowercase[1:] + string.lowercase[0]))

This is just a dictionary, so using, e.g., letter_map['c'] will produce 'd'.

In the above, string.lowercase is just a string containing the lowercase letters. The value will depend on your locale. If you only want 'abcdefghijklmnopqrstuvwxyz', regardless of locale, you can substitute string.ascii_lowercase or just give the explicit string.

Upvotes: 8

mtrw
mtrw

Reputation: 35088

Depending on what you're doing, you might be interested in string.lowercase and it's cousins.

>>> import string
>>> for let in string.lowercase:
...    print let
...
a
b
c
(etc)

See the documentation for more details.

Upvotes: 1

egor83
egor83

Reputation: 1237

idx = 0
while condition:
    lett = chr(idx + ord('a'))
    idx += 1
    if idx == 26:
        idx = 0

See ord, chr

Upvotes: 1

ChrisF
ChrisF

Reputation: 137128

The ASCII codes for letters are consecutive. So 65 = 'A', 66 = 'B' and so on - ASCII table you could use a normal loop.

Start at 97 (lower case 'a') and loop using normal incrementing and then convert the loop counter to it's equivalent character for output.

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601529

Try something like

chr(x + ord("a"))

where x is an integer in the range 0 to 25.

ord() returns the ASCII code of a character, and chr() turns an ASCII code into a character again. In ASCII, the lower case letters all appear consecutively (in contrast to EBCDIC for those who still remember).

Upvotes: 4

Related Questions