python 内置函数(一)

这篇博客介绍了Python的四个内置函数:abs()用于获取数字的绝对值,all()检查所有元素是否为真,any()判断是否存在一个真值元素,ascii()生成对象的可打印字符串,转义非ASCII字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

abs() 数字取绝对值

内置函数 abs(),Python 官方文档描述如下:

help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

返回一个数的绝对值,参数可以是整数、浮点数或任何实现了 __abs__() 的对象。如果参数是一
个复数,则返回它的模。

abs(-1)
1
abs(-3.14)
3.14
abs(3+4j)
5.0

all() 所有元素布尔值为真?

内置函数 all(),Python 官方文档描述如下:

help(all)
Help on built-in function all in module builtins:

all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.

如果可迭代对象(iterable)的所有元素均为真值(或可迭代对象为空)则返回 True 。

all('0123') # 字符串 '0' 是真值
True
all([0,1,2,3])
False
all({})
True
all({1:[], 2:0 })
True

any() 有一个元素布尔值为真?

内置函数 any(),Python 官方文档描述如下:

help(any)
Help on built-in function any in module builtins:

any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.

如果可迭代对象(iterable)的任一元素为真值则返回 True。如果可迭代对象为空,返回 False。

any([0,1])
True
any((None, [], range(1,1)))
False

ascii() 返回对象的可打印字符串

内置函数 ascii(),Python 官方文档描述如下:

help(ascii)
Help on built-in function ascii in module builtins:

ascii(obj, /)
    Return an ASCII-only representation of an object.
    
    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \\x, \\u or \\U escapes. This generates a string similar
    to that returned by repr() in Python 2.

就像函数 repr(),返回一个对象可打印的字符串,但是非 ASCII 编码的字符,会使用 \x、\u 和 \U 来转义。

ascii(123)
'123'
ascii(None)
'None'
ascii('python')
"'python'"
ascii('嗨')
"'\\u55e8'"
repr('嗨')
"'嗨'"
'\u55e8' # 16 位十六进制数 55e8 码位的字符
'嗨'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值