Nicolas Mailloux
Nicolas Mailloux

Reputation: 69

Python converting letter to two-digit number

little noob in Python here. I'm doing a small personal project and I would want to convert a simple string

str='test"

to something like that:

['20', '05', '19', '20']

which would equal to 'test' in two-digit numbers. I found the 'ord' method, but it seems to convert the numbers in integer format and leave them with only one digit where it is not necessary to have two. However for my project I need those two digits and not in integer format (it's a DTMF message encoder/decoder that works with a 01-99 range of codes, which equals to one letter/symbol per number).

Any help?

Thanks!

Upvotes: 2

Views: 1798

Answers (2)

Joe Ferndz
Joe Ferndz

Reputation: 8508

Here's a way to do this.

updated code:

[f'{ord(i)-96:02d}' for i in 'test'.lower()]

earlier code:

["{:02d}".format((ord(i)-96)) for i in 'test']

This will result in:

['20', '05', '19', '20']

The above code uses .format option, list comprehension, and ord() function Please go through them. Links attached.

Upvotes: 2

Amin Pial
Amin Pial

Reputation: 511

You might want to do this with zfill and get the index from ascii_lowercase (as suggested in the comments) though it's a bit messy. Doing this with ord and string formatting is surely the elegant way as Joe answered.

from string import ascii_lowercase as al
[str(al.index(x)+1).zfill(2) for x in "test"] # ['20', '05', '19', '20']

Well, we can use caching with dict for faster look up like below:

from string import ascii_lowercase as al
cache = {char: idx+1 for idx, char in enumerate(al)}
[str(cache[x]).zfill(2) for x in "test"] # ['20', '05', '19', '20']

Upvotes: 0

Related Questions