I very new to programming and I have a simple problem that I just do not know the syntax to. I have a regular text file that I want to substitute all of the letters for numbers. i.e. if I find an “a” or an “A”, I want to substitute the number “1”. If I find a “b” or “B” I want to substitute the number “2” ect. Can someone help me with this, I know it is most basic but I am trying to learn to program on my own and it is quite difficult. Thank-you!
Share
This is something of an overcomplicated answer, but it has several useful Python concepts which you should at some stage learn. Here’s the simple version:
The first line handles opening (and closing) the file. The second iterates over all the lines of the file. The third iterates over each character in the line. The fourth checks to see whether the character is a letter or not (what is the number of “.”, say?). The fifth does the magic:
ordchanges a letter into its ASCII code, which is an integer. Since the codes don’t start at one, you have to subtract the code of “a” first.As an exercise for later, here’s a more generic version that takes any string and
yields the characters in the string one at a time. Let me know if you want me to explain it.