Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: How do I assign values to letters?

I want to assign a value to each letter in the alphabet, so that a -> 1, b -> 2, c -> 3, ... z -> 26. Something like a function which returns the value of the letter, for example:

value('a') = 1

value('b') = 2

etc...

How would I go about doing this in python?

like image 651
Eddy Avatar asked Jul 14 '10 12:07

Eddy


4 Answers

You want a native python dictionary.

(and you probably also want your values to start from"0" not from "1" , so you can void adding a +1 on all your mappings, as bellow)

Build one with this:

import string
values = dict()
for index, letter in enumerate(string.ascii_lowercase):
   values[letter] = index + 1

This give syou things like:

print values["a"]
-> 1

Of course, you probably could use the "ord" built-in function and skip this dictionary altogether, as in the other answers:

print ord("c") - (ord("a")) + 1

Or in python 3.x or 2.7, you can create the dicionary in a single pass with a dict generator expression:

values = {chr(i): i + 1 for i in range(ord("a"), ord("a") + 26)}
like image 137
jsbueno Avatar answered Oct 12 '22 22:10

jsbueno


If you just want to map characters of the ASCII alphabet to numbers, you can use ord() and then adjust the result:

>>> ord('a') - 96
1

If you want this to work for uppercase letters too:

>>> ord('A'.lower()) - 96
1

Also, you might want to validate that the argument is indeed a single ASCII character:

>>> char = 'a'
>>> len(char) == 1 and char.isalpha() and 'a' <= char <= 'z'
True

Or:

>>> import string
>>> len(char) == 1 and char in string.ascii_lowercase
True
like image 24
Ben James Avatar answered Oct 12 '22 22:10

Ben James


def value(letter):
    return ord(letter) - ord('a') + 1
like image 37
Ned Batchelder Avatar answered Oct 12 '22 23:10

Ned Batchelder


Use a dictionary for key:value pairs. Although for a simple mapping like this there are probably some clever ways of doing this.

like image 36
Mad Scientist Avatar answered Oct 12 '22 22:10

Mad Scientist