954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

letters to numbers

Is there a built-in function to give the value of a letter?

what I mean is
a=1
b=2
c=3
d=4
e=5
f=6
...

something like letval(a) would give me 1

Kruptein
Posting Whiz in Training
258 posts since Sep 2009
Reputation Points: 25
Solved Threads: 11
 

You mean something like this ...

def letval(x):
    print(x)

a = 77
letval(a)

# you can just use
print(a)
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

No I don't mean that, that would be stupid.
every letter of the alphabet represents a number
a = the first letter = the first number = 1
b = the second letter = the second number = 2
...
so if I did:

letval(a) #=1
letval(g) #=7 because g is the seventh letter in the alphabet
Kruptein
Posting Whiz in Training
258 posts since Sep 2009
Reputation Points: 25
Solved Threads: 11
 

hint: use ord("a") .

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

hm okay, but in that case I have to make a difference between caps and lowercase letters,... but I will work with that.

Kruptein
Posting Whiz in Training
258 posts since Sep 2009
Reputation Points: 25
Solved Threads: 11
 

Convert them all to lower case before using ord:

l =  l.lower()
scru
Posting Virtuoso
1,629 posts since Feb 2007
Reputation Points: 975
Solved Threads: 140
 

If you are only interested in the letter's position in the alphabet, you can use something like this ...

import string

def letter_position(letter):
    ucase = string.uppercase
    pos = ucase.find(letter.upper()) + 1
    if pos:
        print( "%s has position %d in the alphabet" % (letter, pos) )

letter_position('E')
letter_position('f')
letter_position('a')
letter_position('Z')
letter_position('8')  # a number gives no response
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

That's the one I needed! thanks

Kruptein
Posting Whiz in Training
258 posts since Sep 2009
Reputation Points: 25
Solved Threads: 11
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You