我的Python ASCII代码存在问题,当我尝试将字母转换为ASCII时,它会将ASCII中的数字转换为更多的ASCII代码。我该如何解决这个问题?
Choice = input("Now tell us which code language you like to convert this to Binary or ASCII: \n")
Code = input("Insert your code here, it converts letters to Binary/ASCII: \n\n")
Zero = '048'
One = '049'
Two = '050'
Three = '051'
Four = '052'
Five = '053'
Six = '054'
Seven = '055'
Eight = '056'
Nine = '057'
NewCode = Code.replace('0', Zero)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('1', One)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('2', Two)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('3', Three)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('4', Four)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('5', Five)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('6', Six)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('7', Seven)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('8', Eight)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('9', Nine)
print(NewCode, '\n\n')
time.sleep(0.1)
答案 0 :(得分:1)
您尝试做的事情可以在一行中完成,而无需对字符的ASCII码进行硬编码:
code = '3210' # Do not use initial upper-case letters for variable names!
newCode = ''.join('{:03}'.format(ord(n)) for n in code)
# '051050049048'
然而,您的锻炼目的仍不明确。还要注意' 0XY'通常意味着' XY'写在八进制数系统中。因此,X和Y都不能是8或9。
答案 1 :(得分:1)
问题是替换字符串包含的字符将被后来的.replace()
调用替换。
一种解决方案是一次处理输入一个字符,而不是在整个字符串上使用.replace()
。
BTW,Python有一个ord()
函数,它返回一个字符的代码,通常是ASCII。
NewCode = ''
for char in Code:
NewCode += str(ord(char)).zfill(3)
答案 2 :(得分:0)
您的问题是您不断修改NewCode
,以便在每一步继续修改自己,将数字更改为其ASCII数字。不要为每个NewCode
语句重用replace
,而是使用新变量作为缓冲区。
Code = '3210'
NewCode = Code.replace('', Zero) #NewCode is now 321048
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('4', Four) #The '4' near the end of '321048' gets replaced with '052' making NewCode = 32100528
print(NewCode, '\n\n')
time.sleep(0.1)
答案 3 :(得分:0)
我会这样做,它确保你不要使用缓冲区两次更改ascii代码。
Code = raw_input("Insert your code here, it converts letters to Binary/ASCII: \n\n")
lst_words = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
lst_numbers = ['048','049','050','051','052','053','054','055','056','057']
for i in range(10):
Code = Code.replace(str(i), lst_words[i])
print(Code)
for i in range(10):
Code = Code.replace(lst_words[i], lst_numbers[i])
print(Code)