在Python中,将字符串转换为Unicode编码通常意味着将字符串转换为Unicode码点表示的字符串。以下是几种常见的方法:
1. 使用`str.encode()`方法将字符串编码为Unicode码点表示的字节串:
unicode_str = "你好,世界!"encoded_bytes = unicode_str.encode("utf-8")print(encoded_bytes)
2. 使用`bytes.decode()`方法将字节串解码为Unicode码点表示的字符串:
encoded_bytes = b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'decoded_unicode_str = encoded_bytes.decode("utf-8")print(decoded_unicode_str)
3. 使用`ord()`函数获取字符的Unicode码点,然后格式化为Unicode码点表示的字符串:

def str_to_unicode(string, upper=True):return ''.join(f'\\u{ord(x):04X}' if upper else f'\\u{ord(x):04x}' for x in string)text = "hello中国"lower_uni = str_to_unicode(text, upper=False)upper_uni = str_to_unicode(text)print(lower_uni)print(upper_uni)
4. 使用`chr()`函数将Unicode码点转换为对应的字符:
unicode_code = 0x9500unicode_char = chr(unicode_code)print(unicode_char)
以上方法可以帮助你在Python中转换字符串为Unicode编码
