Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

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']

Post a Comment for "Python Converting Letter To Two-digit Number"