繁体   English   中英

将数字值转换为ASCII字符?

[英]Convert number values into ascii characters?

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

接受字符串

print "This program reduces and decodes a coded message and determines if it is a palindrome"
string=(str(raw_input("The code is:")))

改成小写

string_lowercase=string.lower()
print "lower case string is:", string_lowercase

去除特殊字符

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])时,看起来好像有列表列表,而不是整数列表。 这意味着稍后当您chr(i) for i in result调用chr(i) for i in result ,您将向chr()传递列表而不是int。

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

其他小建议:

  • raw_input已经为您提供了一个字符串,因此无需显式转换它。
  • 删除特殊字符可以更有效地编写为:

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

    这使您只需要遍历string_lowercase一次,而不用遍历special_characters的每个字符。

当列表仅接受整数时,您会将其传递给chr 尝试result.append(code-offset) [code-offset]是一个单项列表。

具体来说,代替:

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

采用:

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

如果您了解列表理解,也可以使用: result = [ord(i)-offset for i in string_lowercase]

在执行.append()列出时,请使用code-offset而不是[code-offset] 与稍后一样,您将值存储为一个(一个ASCII)列表,而不是直接存储ASCII值。

因此,您的代码应为:

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

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

result = [ord(ch)-offset for ch in string_lowercase]

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

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM