如何用Python制作简单的字节到字符串转换器?

0 投票
2 回答
49 浏览
提问于 2025-04-14 17:30

我正在尝试制作一个简单的转换器,但遇到了以下错误:
AttributeError: 'str'对象没有'decode'这个属性。你是想说'encode'吗?

或者

TypeError: 不支持对字符串进行解码

我首先尝试了一个例子,使用字符ã

当我执行

    encodedcharacter = input("Encode a str: ")
    print(encodedcharacter.encode('utf-8'))

时,返回的是

b'\xc3\xa3'

但是当我把这个输入进去并尝试解码时

encodedcharacter = input("Encode a str: ") # I entered "b'\xc3\xa3'"
print(encodedcharacter.decode('utf-8'))

返回的是

Traceback (most recent call last):
  File "/path/to/decode_test.py", line 2, in <module>
    encodedcharacter = input("Encode a str: ")
AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?

我还尝试了

encodedcharacter = input("Encode a str: ") # I entered "b'\xc3\xa3'"
decoded_text = encodedcharacter.encode('utf-8').decode('unicode_escape')
print(decoded_text)

结果是

b'ã'

这个结果差不多……但还是不够准确

2 个回答

0
import ast

encoded_string = input("Enter a byte string: ")  # Enter something like 
"b'\xc3\xa3'"

bytes_object = ast.literal_eval(encoded_string.encode('utf- 
8').decode('unicode_escape'))

# Decode the bytes object to a string
decoded_string = bytes_object.decode('utf-8')

print(decoded_string)

这样,你就可以安全地把字节串转换回字符串。不过,使用 eval()ast.literal_eval() 时一定要小心,特别是当输入来自用户时,因为这样可能会带来执行任意代码的安全风险。

0

这里有一种方法可以做到这一点,而不需要使用 ast.literal_eval。首先,使用正则表达式从输入中提取出十六进制部分(比如 'c3' 和 'a3')。接着,把这些十六进制数转换成整数(比如 195 和 163)。然后,你可以使用内置的 bytearray 把这些整数转换成字节数组。最后,解码这个字节数组。

import re

# ====================
def byte_array_from_string_input(string_input):

    hex_values = re.findall(r"\\x([^\\'\"]+)", string_input)
    int_values = [int(hex, 16) for hex in hex_values]
    as_bytes = bytearray(int_values)
    return as_bytes


encoded_string = input("Enter a byte string: ")
decoded = byte_array_from_string_input(encoded_string).decode('utf-8')
print(f'Here is your decoded string:', decoded)

在解释器中运行这个:

Enter a byte string: \xc3\xa3
Here is your decoded string: ã

byte_array_from_string_input 这个函数无论用户是否在输入前后加上 b'' 都能正常工作。

撰写回答