Using python to achieve English alphabet and corresponding ordinal conversion
Step 1: Letter to Number
The alphabetic number is relatively simple. You can input a line of English alphabet that needs to be converted on the command line, then match each letter in the alphabet, and return the corresponding digits, then accumulate these digits. In order to make the results more readable, how to add spaces between the adjacent numbers and commas between the corresponding original words are added.
c="abcdefghijklmnopqrstuvwxyz" temp='' list=[] s=input() num=len(s) list.append(s) for i in range(0,num): if list[0][i]==' ': temp+=',' else: for r in range(1,26): if list[0][i]==c[int(r)-1]: temp+=str(r) temp+=' ' print("The output results are as follows:%s"%temp)
Step 2: Number to letter
The difficulty of digit-to-alphabet conversion is how to reasonably take out each corresponding digit when a line of digits is input.
- Then I began to think of using regular matching, fixed pattern unit ( d+,{0,}), and then I wanted each number to return a tuple in the form of. groups(), but I was limited to the number of places to input numbers, so I could not find a good matching way.
- Then the split() function is used to split a string with the corresponding separator, and the value is returned in the form of a list.
c="abcdefghijklmnopqrstuvwxyz" temp='' s=input() s_list=s.split(",") num=len(s_list) for i in range(0,num): if s_list[i]==' ': temp+=' ' else: result=c[int(s_list[i])-1] temp+=result print("The output is:%s"%temp)
Complete code
#-*- coding: utf-8 -*- import re def main(): ss=input("Please choose:\n1.Letter->number\ \n2.number->Letter\n") if ss=='1': print("Please enter letters: ") fun1() elif ss=='2': print("Please enter the number:") fun2() def fun1(): c="abcdefghijklmnopqrstuvwxyz" temp='' list=[] s=input() num=len(s) list.append(s) for i in range(0,num): if list[0][i]==' ': temp+=',' else: for r in range(1,26): if list[0][i]==c[int(r)-1]: temp+=str(r) temp+=' ' print("The output results are as follows:%s"%temp) def fun2(): c="abcdefghijklmnopqrstuvwxyz" temp='' s=input() s_list=s.split(",") num=len(s_list) for i in range(0,num): if s_list[i]==' ': temp+=' ' else: result=c[int(s_list[i])-1] temp+=result print("The output is:%s"%temp) if __name__ == '__main__': main()
You can use the python code to realize the conversion between English letters and numbers.