用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