用python实现英文字母和相应序数转换
第一步:字母转数字
英文字母转对应数字相对简单,可以在命令行输入一行需要转换的英文字母,然后对每一个字母在整个字母表中匹配,并返回相应的位数,然后累加这些位数即可。过程中,为了使结果更有可读性,输出相邻数字间怎加了空格,每个对应原来单词间增加逗号。
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("输出结果为:%s"%temp)
第二步:数字转字母
数字转字母有个难点就是,当输入一行数字,如何才能合理地把它们每个相应位的数取出来。
- 才开始想到用正则匹配,定模式单元(\d+,{0,}),然后希望每个数字用.groups()形式返回一个元组(tuple),但限于要输入数字的个数位置,没找到好的匹配方式。
- 然后用到了split()函数,用相应的分隔符分割一段字符串之后,将值已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("输出结果是:%s"%temp)
完整代码
#-*- coding: utf-8 -*-
import re
def main():
ss=input("请选择:\n1.字母->数字\
\n2.数字->字母\n")
if ss=='1':
print("请输入字母: ")
fun1()
elif ss=='2':
print("请输入数字:")
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("输出结果为:%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("输出结果是:%s"%temp)
if __name__ == '__main__':
main()
便可利用该python代码实现英文字母和对应数字的相互转换。
**附加
1.其他方法
除了以上这种方法,还可以借助ascii码连续性来转换字母和相应的序数。
字母转数字
s=input("请输入字母")
temp=''
for i in range(0,len(s)):
if s[i]==' ':
temp+=','
else:
m=ord(s[i])-96
temp+=str(m)
temp+=" "
print("输出结果为:%s\n"%temp)
数字转字母
s=input("请输入数字:")
s_list=s.split(',')
temp=''
for i in range(0,len(s_list)):
if s_list[i]==' ':
temp+=' '
else:
m=chr(int(s_list[i])+96)
temp+=m
print("输出结果为:%s"%temp)
2.其他启发
用ASCII码来实现字母和数字转换是一个很好的途径,因为她们都有连续的特性,加减之后会得到对应的值。
- 例如:实现16进制数转10进制
s=input("请输入16进制数[格式为0xaaa]:\n")
s=s[2:]
result=0
num=n=len(s)
for i in range(0,n):
try:
if(int(s[num-1]) in range(0,9)):
result+=int(s[num-1])*pow(16,n-num)
num-=1
except:
if(ord(s[num-1]) in range(97,101)):
result+=(ord(s[num-1])-87)*pow(16,n-num)
num-=1
elif(ord(s[num-1]) in range(65,69)):
result+=(ord(s[num-1])-55)*pow(16,n-num)
num-=1
print(result)
当然,python提供了转十进制和十六进制之间的函数:
hex(10) #10进制转16进制 结果为:a
int('a',16)或int('0xa',16) #16进制转10进制 结果为:10