python - 制作一个八进制到 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 语句中。有任何想法吗?
解决方案
您需要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)
)。
推荐阅读
- sql - 如何打印产生多类 case 语句结果的匹配模式?
- sql - 我有 DD-MON-RR HH24.MI.SS 格式的日期要插入到 oracle 表中,如何在 CTL 文件中定义日期?
- php - PHP在做数学减法之前用前导点格式化千数?
- python - 我的碰撞检测无法正常工作
- c - Openssl 签名生成 JWT 令牌
- vega-lite - Vega-lite:字段出现在错误的图表中?
- r - 如何在 R 中绘制理论帕累托分布?
- .net-core - 带有 ODataClient 的 Blazor - 缺少位置标头
- r - 转换日期数据框
- ansible - Ansible get_url 模块:找不到文件的校验和