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)  # 输出字符串"你好"

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值