把数值转换成ascii字符?

2024-10-06 07:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从我得到的数值到字符来拼出一个不起作用的单词,它说我需要在最后一部分使用一个整数?在

接受字符串

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))

Tags: andtheinforinputstringrawis
3条回答

当您调用result.append([code-offset])时,它看起来像是一个列表列表而不是一个int列表。这意味着稍后当您调用chr(i) for i in result时,您将向chr()传递一个列表而不是一个int。在

尝试将其更改为result.append(code-offset)。在

其他小建议:

  • ^{}已经为您提供了一个字符串,因此不需要显式转换它。在
  • 删除特殊字符可以更有效地写成:

    special_characters = '1234567890~`!@#$%^&*()_-+={[}]|\:;'<,>.?/'
    string_lowercase = ''.join(c for c in string_lowercase if string not in special_characters)
    

    这允许您只需迭代一次string_lowercase,而不是special_characters中的每个字符。

当对列表执行.append()操作时,请使用code-offset而不是{}。与后面一样,您将值存储为一个列表(一个ASCII),而不是直接存储ASCII值。在

因此,您的代码应该是:

result = []
for i in string_lowercase:
    code = ord(i)
    result.append(code-offset)

但是,您可以将此代码简化为:

^{pr2}$

您甚至可以进一步简化代码。获得解码字符串的一行是:

decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase)

示例偏移量为2:

>>> string_lowercase = 'abcdefghijklmnopqrstuvwxyz'
>>> offset = 2
>>> decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase)
>>> decoded_string
'_`abcdefghijklmnopqrstuvwx'

您正在向chr传递一个列表,而它只接受整数。尝试result.append(code-offset)[code-offset]是一个单项列表。在

具体来说,不是:

result=[]
for i in string_lowercase:
    code=ord(i)
    result.append([code-offset])

使用:

^{pr2}$

如果你理解列表理解,这也行得通:result = [ord(i)-offset for i in string_lowercase]

相关问题 更多 >