python中ord()函数的用法,返回Unicode编码

ord()函数描述

ord()函数是python内置的可用于查询字符的Unicode编码的内置函数,接收一个字符为参数,返回该字符串的Unicode编码值。


ord()函数语法结构

该函数的语法结构来源python源码:

def ord(c: Union[Text, bytes])

ord()函数的参数和返回值

python中ord()的源码有这么一句话:Return the Unicode code point for a one-character string.即接收的参数为one-character string(长度为1的字符,下面的实例中会有python的提示),返回值为Unicode code。


ord()函数实例代码

>>> ord('3')
51
>>> ord(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected string of length 1, but int found
>>> ord('ab')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found

代码解析

如上实例代码,当将int类型的数据1作为参数传递给ord()函数时,python抛出TypeError,并提示ord() expected string of length 1, but int found,即ord()函数接收长度为1的字符串作为参数,当传递长度为2的'ab'作为参数时,python的TypeError进一步验证了这一点。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.