-1

text_box is a tkinter text box I am trying to convert source_text's letters to the number corresponding to the position of said letter such that a or A = 1, b or B = 2 and print it the console

    def enter():
    #don't use 1 in place of 1.0
    source_text=text_box.get(1.0, END)
    

    def alphabet_position(text):

        dict = {'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'}
        new_text = text.lower(source_text)
        for i in new_text:
            if i in dict:
                new_text = new_text.replace(i, dict[i])
            print (new_text)

enter is called as such

btn = Button(root, text = "Enter", command = enter)
  • Could you show how you are calling the functions, and explain where you are having issues? – Erik McKelvey Nov 12 '21 at 17:41
  • Are you asking how to convert `'a'-'z'` to `1-26`? If so, you should rename the question and the best way is to use `ord`. In this case `ord(ch) - ord('a') + 1` will do the conversion correctly if `ch` one of `'a'-'z'`, i.e. if `len(ch) == 1 and ch.isalpha()`. – joseville Nov 12 '21 at 17:46
  • Does this answer your question? [Convert alphabet letters to number in Python](https://stackoverflow.com/questions/4528982/convert-alphabet-letters-to-number-in-python) – joseville Nov 12 '21 at 17:48
  • no I am not asking how to convert 'a'-'z' to 1-26. sorry I am very new to coding and am a little confused – Derek Neilson Nov 12 '21 at 17:48
  • ```print (new_text)``` dose not print new_text – Derek Neilson Nov 12 '21 at 17:54
  • `print (new_text)` is strangely indented. – hpchavaz Nov 12 '21 at 18:07
  • In the loop, You are modifying the string you are looping on, it is rarely a good idea. – hpchavaz Nov 12 '21 at 18:09
  • `string.lower()` does not takes a parameter. – hpchavaz Nov 12 '21 at 18:14
  • as pointed out by @hpchavaz, `new_text = text.lower(source_text)` is not valid. See [str.lower()](https://docs.python.org/3/library/stdtypes.html?highlight=lower#str.lower) – SanV Nov 12 '21 at 18:38
  • ok so how do I tell it to accept ```source_text ``` as a input note that ```source_text``` was redacted in ```text.lower(source_text)``` – Derek Neilson Nov 12 '21 at 18:42
  • what I want to do is bring ```new_text``` back in the global scope – Derek Neilson Nov 12 '21 at 19:26

1 Answers1

0
        dict = {'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'}
        new_text = text.lower()
        for i in new_text:
            if i in dict:
                return new_text.replace(i, dict[i])

def enter():
    print (alphabet_position(text_box.get(1.0, END)))