未命名

题目:将字符串按utf8编码格式转换为字节数组并返回对应的十六进制字符串

Python 3 中,字符串用 str.encode('utf-8') 按 UTF-8 编码为 bytes,再用 .hex() 得到十六进制字符串。


def utf8_to_hex(s: str) -> str:
    """
    将字符串按 UTF-8 编码转换为字节数组,
    并返回对应的十六进制字符串(小写)。
    """
    byte_data = s.encode('utf-8')  # bytes,可看作字节数组
    return byte_data.hex()

示例:


s = "Hello, 世界"
byte_data = s.encode('utf-8')
hex_str = byte_data.hex()
print(byte_data)      # b'Hello, \xe4\xb8\x96\xe7\x95\x8c'
print(list(byte_data))  # [72, 101, 108, 108, 111, 44, 32, 228, 184, 150, 231, 149, 140]
print(hex_str)        # 48656c6c6f2c20e4b896e7958c

未命名
https://mingsm17518.github.io/2026/09/30/刷题笔记/机考-虾皮信息/第2题/
作者
Ming
发布于
2026年9月30日
更新于
2026年10月2日
许可协议