gpt4 book ai didi

python - chr() 和 ord() 如何与 str 和 bytes 相关?

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:41 25 4
gpt4 key购买 nike

我在 chr 上找到了 Python 3 文档和 ord有点不清楚它们与两种主要文本数据类型的关系:strbytes。或者我想多了。

这是我认为可能会发生的情况,但如果我是对的,你能告诉我吗?

  • ord() 将单字符 str 作为输入并返回 int。输入是 str ,就像 Python 3 中的任何其他 str 一样。特别是,它是不是 bytes 编码的在某些特定的 Unicode 格式(如 UTF-8)中,它代表 Python 内部 str 格式的 Unicode 代码点。
  • chr()int 作为输入,并返回单个字符 str。返回的 str 与 Python 中的任何其他 str 一样,同样不是使用 bytes 的特定编码。
  • ord()chr() 绝不会处理 bytes,它们也不处理特定的 Unicode 格式,例如 UTF -8,它们只处理 Python 的内部 str 表示,它更抽象地处理 Unicode 代码点。

最佳答案

你是对的。

ord()chr() 仅处理单字符字符串。

他们的文档对此非常清楚:

>>> help(ord)
ord(c, /)
Return the Unicode code point for a one-character string.

>>> help(chr)
chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

使用 str.encode/bytes.decode 进行字节转换。

关于python - chr() 和 ord() 如何与 str 和 bytes 相关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50011314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com