0

Is there any "easy" way to convert a string of letters to an integer value? I know a method that would work, but it would be very tedious. Oh and in Python, I forgot to mention that. It would be like "ABC" = 123

2
  • 3
    What would "XYZ" translate to? Commented Jan 25, 2017 at 18:33
  • Yes, that's quite a good question... Commented Jan 25, 2017 at 18:39

3 Answers 3

1

Pre-define a dictionary that maps letters to numbers:

d = {'A': '1', 'B': '2', 'C': '3', 'D': '4',
     'E': '5', 'F': '6', 'G': '7', 'H': '8',
     'I': '9', 'J': '10', 'K': '11', 'L': '12',
     'M': '13', 'N': '14', 'O': '15', 'P': '16',
     'Q': '17', 'R': '18', 'S': '19', 'T': '20',
     'U': '21', 'V': '22', 'W': '23', 'X': '24',
     'Y': '25', 'Z': '26'}

Then you can convert with:

int(''.join(d[c] for c in 'ABC'))
Sign up to request clarification or add additional context in comments.

Comments

1
print ([ord (c) - ord ('A') + 1 for c in 'ABC'])

N.B. Rob's answer is better... (upto the 'i' ;=))

1 Comment

Thanks, this is what i needed
0

Your problem is underspecified. There are literally infinite functions that will convert 'ABC' to 123, including this one:

def letter2number(s):
    return 123

If you want to covert the strings by concatenating the decimal digits of the letter's offset into the alphabet, this one might work for you. Note that you can't round-trip the value: 24 could be X or it could be BD.

def letter2number(s):
    return int(''.join('%d'%(ord(ch)-ord('A')+1) for ch in s))

assert letter2number('ABC') == 123
assert letter2number('XYZ') == 242526

3 Comments

So add 100 to each code (to keep it simple) and then glue together.
But then 'ABC' won't yield 123, which was a requirement.
Indeed. So it would need to be a variable lenght code, perhaps with the 0 as extension indicator. But I guess that's not what OP was looking for...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.