我需要从我得到的数值到字符来拼出一个不起作用的单词,它说我需要在最后一部分使用一个整数?在
接受字符串
print "This program reduces and decodes a coded message and determines if it is a palindrome"
string=(str(raw_input("The code is:")))
把它改成小写
^{pr2}$去除特殊字符
specialcharacters="1234567890~`!@#$%^&*()_-+={[}]|\:;'<,>.?/"
for char in specialcharacters:
string_lowercase=string_lowercase.replace(char,"")
print "With the specials stripped out the string is:", string_lowercase
输入偏移量
offset=(int(raw_input("enter offset:")))
文本到ASCII码的转换
result=[]
for i in string_lowercase:
code=ord(i)
result.append([code-offset])
从ASCII码到文本的转换
text=''.join(chr(i) for i in result)
print "The decoded string is:", text.format(chr(result))
当您调用
result.append([code-offset])
时,它看起来像是一个列表列表而不是一个int列表。这意味着稍后当您调用chr(i) for i in result
时,您将向chr()
传递一个列表而不是一个int。在尝试将其更改为
result.append(code-offset)
。在其他小建议:
删除特殊字符可以更有效地写成:
这允许您只需迭代一次
string_lowercase
,而不是special_characters
中的每个字符。当对列表执行}。与后面一样,您将值存储为一个列表(一个ASCII),而不是直接存储ASCII值。在
.append()
操作时,请使用code-offset
而不是{因此,您的代码应该是:
但是,您可以将此代码简化为:
^{pr2}$您甚至可以进一步简化代码。获得解码字符串的一行是:
示例偏移量为2:
您正在向
chr
传递一个列表,而它只接受整数。尝试result.append(code-offset)
。[code-offset]
是一个单项列表。在具体来说,不是:
使用:
^{pr2}$如果你理解列表理解,这也行得通:
result = [ord(i)-offset for i in string_lowercase]
相关问题 更多 >
编程相关推荐