Bootstrap

python获取字符编码

在Python中,您可以使用内置的ord()函数获取单个字符的Unicode编码,使用encode()方法获取字符串的字节编码。

获取单个字符的Unicode编码:

char = 'a'
unicode_code = ord(char)
print(unicode_code)  # 输出字符的Unicode编码

获取字符串的字节编码:

text = "hello"
byte_encoding = text.encode()
print(byte_encoding)  # 输出字符串的字节编码

s1 ="你"
r = ord(s1)
print(f'汉字"{s1}"的unicode编码是:{r}')
# 循环获取字符串的每个字符的Unicode编码
str1 ="hello你"
unicode_codes = [ord(char) for char in str1]
print(f'汉字"{str1}"的unicode编码是:{unicode_codes}')

您还可以指定编码格式来获取特定编码的字节串:

text = "你好"
utf8_encoding = text.encode('utf-8')
print(utf8_encoding)  # 输出UTF-8编码的字节串

解码字节串为字符串:

byte_str = b"hello"
decoded_str = byte_str.decode()
print(decoded_str)  # 输出字符串"hello"

指定解码格式:

utf8_bytes = b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded_text = utf8_bytes.decode('utf-8')
print(decoded_text)  # 输出字符串"你好"

;