首页 > 解决方案 > 制作一个八进制到 UTF-8 的转换器(仅限英文字母)。什么是八进制转义字符

问题描述

我正在 python 中做一个不和谐的机器人(使用 discord.py API),并且一直使它与十六进制、莫尔斯和 base64/32 字符串一起工作,我现在正试图让它解码八进制字符串。

我一直在做一些研究,发现这篇文章Python - Convert Octal to non-English Text from file和其他类似的文章试图用所谓的“八进制转义字符”转换非英语字符。我知道转义字符是什么,我知道八进制字符是什么,但我不知道那些转义字符是做什么的。

无论如何,我只需要它来读取一个普通的八进制字符串并将其解码为单词。没有涉及外来字符,所以我真的希望有一个更简单的方法来做到这一点

例如,110 145 154 154 157 40 151 156 164 145 162 156 145 164 应翻译为“hello internet”

我发现其他只有英文字符的帖子,但它们都是针对 java 的。这是我到目前为止所得到的:

    #Bot is listening for message. If it finds one message which starts with !decodeoctal It'll execute the inside of the conditional (the decoder itself)
    if message.content.startswith('!decodeoctal'):

        #The content of the message is now a list inside a variable called msglist               
        msglist = message.content.split()

        #The first item of the list (the one that contains the !decodeoctal string) is discarded leaving the rest of list, that contains the octal string intact
        msglist = msglist[1:]                       
            try:    
                #Code dor decoding the string goes here                                                 
            except:                         
                msg = '''Decoding error.'''
                await client.send_message(message.channel, msg)

代码是一级缩进的,因为它位于另一个 if 语句中。有任何想法吗?

标签: python

解决方案


您需要chr将数字转换为字符。

msglist是具有字符串值'110''145'等的字符串列表'154'。如果您想将它们提供给chr您,则必须根据这些值创建数字。这就是int进来的地方。int有一个基数参数,8因为你有八进制值。

values = []
for octal_string in msglist:
    number = int(octal_string, base=8)
    values.append(number)
print(''.join(chr(value) for value in values))

简洁版本:

print(''.join(chr(int(octal_string, base=8)) for octal_string in msglist))

正如评论中所要求的,这里有更多关于int. int将字符串转换为数字。'100'100是两个不同的东西。只是尝试print(99 < 100)print('99' < '100')。使用int很简单:int('100')会给我们100.

但是如果'100'不是十进制数字而是二进制怎么办?int仍然可以进行转换,但我们必须指定基数(10默认情况下)。所以现在我们使用int('100', base=2)并获取4.

八进制系统 '100'中将导致十进制值64( int('100', base=8)),而100十六进制中将导致十进制值256( int('100', base=16))。


推荐阅读