0

Using a dictionary...

import string
alphabet = string.ascii_lowercase
alphabet1 = string.ascii_uppercase

a = "This is some string"


b = dict()
for i in range(len(alphabet)):
    b[i] = alphabet[i]
    
c = dict()
for i in range(len(alphabet1)):
    c[i] = alphabet1[i]

halfway there...don't know how to employ the for/while iterative loop to output the numeric sequence associated w/ "This is some string"; e.g., [19, 7, 8, ...]

Regards.

user01
  • 13
  • 3
  • Does this answer your question? [How to replace words in a string using a dictionary mapping](https://stackoverflow.com/questions/49600700/how-to-replace-words-in-a-string-using-a-dictionary-mapping) – PM 77-1 Jan 12 '21 at 00:55
  • you've got dictionaries that are character to number, so now you just need to go through each character you the string like: `for character in a:` – Macattack Jan 12 '21 at 01:00

1 Answers1

0

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}
bherbruck
  • 2,167
  • 1
  • 6
  • 17