Michael Molter
Michael Molter

Reputation: 1326

Counting by letters in Python

Objective: count by letters instead of integers.

Is there a clean way to count-by-letters in Python-2.7? I have a program where I am enumerating some data by letter, and my solution would not be very clear to someone reading my code.

I've been checking through the standard documentation, but I don't see anything built-in.

What I'm looking for:

for count in range('A', 'G'):
    print count

output[1]:
'C'
'D'
'E'
'F'

How I would do it:

Solution A: Use a dictionary

letters = {
    1:'A'
    2:'B'
    3:'C'
    ...
}

for count in range(2, 6):
    print letters[count]

Solution B: Use chr() and ord()

for count in range(2, 6):
    print chr(ord('A') + count)

Relevance:

I am working on a sunday paper crytogram solver. Part of my algorithm involves classifying words by their letter code. For example,

print letter_code('banana')
output[2]: 'ABCBCB'

Upvotes: 1

Views: 871

Answers (4)

cdlane
cdlane

Reputation: 41852

Your Solution B could be expressed:

for charcode in range(ord('B'), ord('G')):
    print chr(charcode)

But to attack your larger issue, how about:

from string import ascii_lowercase, ascii_uppercase

def letter_code(string):
    indexes = [ascii_lowercase.index(letter) for letter in string]
    return "".join(ascii_uppercase[indexes.index(number)] for number in indexes)

print letter_code('banana')

Gives you "ABCBCB"

Upvotes: 1

Michael Molter
Michael Molter

Reputation: 1326

Another solution I have become fond of for my particular application is:

alphabet = iter('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
print next(alphabet)

Upvotes: 0

AimiHat
AimiHat

Reputation: 383

Here is a function that would do what you wish:

import string

def enumerate(first, last):
    alphabet = string.ascii_uppercase
    start = alphabet.index(first)
    while alphabet[start] != last:
        print alphabet[start]
        start += 1
    print last

Upvotes: 0

Bahrom
Bahrom

Reputation: 4862

import string
alphabet = string.ascii_uppercase

>>> for char in alphabet[2:6]:
...     print char
...     
C
D
E
F
>>> 

Upvotes: 2

Related Questions