You can simplify it by swapping the key, value pairs from enumerate(string.ascii_letters)
and then get the index by accessing the value for that key in the resulting dictionary:
from string import ascii_letters
# reverse key, value pairs form ascii_letters for accessibility later
chars = {value: index for index, value in enumerate(ascii_letters)}
def index_string(text):
# access the index for each key if it exists in chars (ascii_letters) and return it as a list
return [chars[char] for char in text if char in chars]
print(index_string("This is some string"))
Output:
[45, 7, 8, 18, 8, 18, 18, 14, 12, 4, 18, 19, 17, 8, 13, 6]
For reference, the chars
dictionary looks like this:
{'a': 0,
'b': 1,
'c': 2,
'd': 3,
'e': 4,
'f': 5,
'g': 6,
'h': 7,
'i': 8,
'j': 9,
'k': 10,
'l': 11,
'm': 12,
'n': 13,
'o': 14,
'p': 15,
'q': 16,
'r': 17,
's': 18,
't': 19,
'u': 20,
'v': 21,
'w': 22,
'x': 23,
'y': 24,
'z': 25,
'A': 26,
'B': 27,
'C': 28,
'D': 29,
'E': 30,
'F': 31,
'G': 32,
'H': 33,
'I': 34,
'J': 35,
'K': 36,
'L': 37,
'M': 38,
'N': 39,
'O': 40,
'P': 41,
'Q': 42,
'R': 43,
'S': 44,
'T': 45,
'U': 46,
'V': 47,
'W': 48,
'X': 49,
'Y': 50,
'Z': 51}