Python 常见百个函数全面剖析
1. 类型转换相关函数
1.1 int()函数
将字符串或数字转换为整数类型。
# 基础使用
int('123') # 输出 123
int(3.14) # 输出 3
# 指定进制转换
int('1010', 2) # 将二进制数1010转为十进制得10
int('FF', 16) # 将十六进制数FF转为十进制得255
# 临界值处理
int('') # 引发 ValueError: invalid literal for int() with base 10: ''
int(None) # 引发 TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
int('3.14') # 引发 ValueError: invalid literal for int() with base 10: '3.14'
int(float('inf')) # 引发 OverflowError: cannot convert float infinity to integer
1.2 float()函数
把数据转换为浮点数类型。
# 基本使用
float('3.14') # 输出 3.14
float(3) # 输出 3.0
# 特殊值转换
float('inf') # 输出 inf
float('-inf') # 输出 -inf
float('nan') # 输出 nan
# 临界值处理
float('') # 引发 ValueError: could not convert string to float: ''
float(None) # 引发 TypeError: float() argument must be a string or a number, not 'NoneType'
float('3.14a') # 引发 ValueError: could not convert string to float: '3.14a'
1.3 str()函数
把对象转换为字符串类型。
# 基本使用
str(123) # 输出 '123'
str(3.14) # 输出 '3.14'
str(True) # 输出 'True'
# 特殊对象转换
str(None) # 输出 'None'
str([1,2,3]) # 输出 '[1, 2, 3]'
# 临界值处理
str(float('inf')) # 输出 'inf'
str(float('nan')) # 输出 'nan'
str(object()) # 输出 '<object object at 0x...>'
1.4 bool()函数
将值转换为布尔类型。
# 基本使用
bool(1) # 输出 True
bool(0) # 输出 False
bool('') # 输出 False
bool('abc') # 输出 True
# 特殊值转换
bool(None) # 输出 False
bool([]) # 输出 False
bool([0]) # 输出 True
# 临界值处理
bool(float('inf')) # 输出 True
bool(float('nan')) # 输出 True
1.5 list()函数
创建列表或者将可迭代对象转换为列表。
# 基本使用
list('abc') # 输出 ['a', 'b', 'c']
list((1,2,3)) # 输出 [1, 2, 3]
# 空列表创建
list() # 输出 []
# 临界值处理
list(None) # 引发 TypeError: 'NoneType' object is not iterable
list(123) # 引发 TypeError: 'int' object is not iterable
list({'a':1}) # 输出 ['a'](字典默认迭代键)
1.6 tuple()函数
创建元组或者将可迭代对象转为元组。
# 基本使用
tuple([1,2,3]) # 输出 (1, 2, 3)
tuple('abc') # 输出 ('a', 'b', 'c')
# 空元组创建
tuple() # 输出 ()
# 临界值处理
tuple(None) # 引发 TypeError: 'NoneType' object is not iterable
tuple(123) # 引发 TypeError: 'int' object is not iterable
1.7 set()函数
创建集合或者去除可迭代对象中的重复元素。
# 基本使用
set([1,2,2,3]) # 输出 {1, 2, 3}
set('aabbcc') # 输出 {'a', 'b', 'c'}
# 空集合创建
set() # 输出 set()
# 临界值处理
set(None) # 引发 TypeError: 'NoneType' object is not iterable
set(123) # 引发 TypeError: 'int' object is not iterable
set([[]]) # 引发 TypeError: unhashable type: 'list'
1.8 dict()函数
创建字典。
# 基本使用
dict(a=1, b=2) # 输出 {'a': 1, 'b': 2}
dict([('a',1),('b',2)]) # 输出 {'a': 1, 'b': 2}
# 空字典创建
dict() # 输出 {}
# 临界值处理
dict(None) # 引发 TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict(123) # 引发 TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict([('a',1), None]) # 引发 TypeError: cannot convert dictionary update sequence element #1 to a sequence
2. 输入输出相关函数
2.9 input()函数
从控制台读取用户输入的字符串。
# 基本使用
# name = input("请输入你的名字: ") # 用户输入会作为字符串返回
# 临界值处理
# 输入Ctrl+D (Unix) 或 Ctrl+Z (Windows) 会引发 EOFError
2.10 print()函数
将指定对象输出到控制台。
# 基本使用
print('Hello', 'World') # 输出 Hello World
print(1, 2, 3, sep='-') # 输出 1-2-3
# 参数说明
# sep: 分隔符,默认是空格
# end: 结束字符,默认是换行符
# file: 输出文件对象,默认是sys.stdout
# flush: 是否立即刷新缓冲区,默认是False
# 临界值处理
print(None) # 输出 None
print(float('inf')) # 输出 inf
print(float('nan')) # 输出 nan
3. 数学运算相关函数
3.11 abs()函数
返回一个数的绝对值。
# 基本使用
abs(-5) # 输出 5
abs(3.14) # 输出 3.14
# 复数绝对值
abs(3+4j) # 输出 5.0(返回模)
# 临界值处理
abs(float('inf')) # 输出 inf
abs(float('-inf')) # 输出 inf
abs(float('nan')) # 输出 nan
3.12 max()函数
返回可迭代对象中的最大值。
# 基本使用
max([1, 2, 3]) # 输出 3
max('a', 'b', 'c') # 输出 'c'
# 指定key函数
max(['apple', 'banana', 'cherry'], key=len) # 输出 'banana'
# 临界值处理
max([]) # 引发 ValueError: max() arg is an empty sequence
max([float('nan'), 1, 2]) # 输出 nan(但比较nan的行为可能不一致)
max([None, 1, 2]) # 引发 TypeError: '>' not supported between instances of 'int' and 'NoneType'
3.13 min()函数
返回可迭代对象中的最小值。
# 基本使用
min([1, 2, 3]) # 输出 1
min('a', 'b', 'c') # 输出 'a'
# 指定key函数
min(['apple', 'banana', 'cherry'], key=len) # 输出 'apple'
# 临界值处理
min([]) # 引发 ValueError: min() arg is an empty sequence
min([float('nan'), 1, 2]) # 输出 nan(但比较nan的行为可能不一致)
min([None, 1, 2]) # 引发 TypeError: '<' not supported between instances of 'int' and 'NoneType'
3.14 sum()函数
对可迭代对象中的元素求和。
# 基本使用
sum([1, 2, 3]) # 输出 6
sum([1.5, 2.5, 3]) # 输出 7.0
# 指定起始值
sum([1, 2, 3], 10) # 输出 16
# 临界值处理
sum([]) # 输出 0
sum(['a', 'b']) # 引发 TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum([float('inf'), 1]) # 输出 inf
sum([float('nan'), 1]) # 输出 nan
3.15 round()函数
对浮点数进行四舍五入。
# 基本使用
round(3.14159) # 输出 3
round(3.14159, 2) # 输出 3.14
# 银行家舍入法(四舍六入五成双)
round(2.5) # 输出 2
round(3.5) # 输出 4
# 临界值处理
round(float('inf')) # 输出 inf
round(float('nan')) # 输出 nan
round(123.456, -2) # 输出 100.0(负的ndigits参数)
round(123.456, 300) # 输出 123.456(过大ndigits参数)
4. 字符串操作相关函数
4.16 len()函数
返回对象的长度或元素个数。
# 基本使用
len('abc') # 输出 3
len([1,2,3]) # 输出 3
len({'a':1}) # 输出 1
# 临界值处理
len('') # 输出 0
len(None) # 引发 TypeError: object of type 'NoneType' has no len()
len(123) # 引发 TypeError: object of type 'int' has no len()
4.17 str.split()函数
以指定字符为分隔符分割字符串。
# 基本使用
'apple,banana,cherry'.split(',') # 输出 ['apple', 'banana', 'cherry']
# 指定最大分割次数
'apple,banana,cherry'.split(',', 1) # 输出 ['apple', 'banana,cherry']
# 临界值处理
''.split(',') # 输出 ['']
' '.split() # 输出 [](默认分割空白字符)
None.split() # 引发 AttributeError: 'NoneType' object has no attribute 'split'
4.18 str.join()函数
用指定字符串连接可迭代对象中的字符串元素。
# 基本使用
','.join(['a', 'b', 'c']) # 输出 'a,b,c'
'-'.join('abc') # 输出 'a-b-c'
# 临界值处理
''.join([]) # 输出 ''
','.join([1, 2, 3]) # 引发 TypeError: sequence item 0: expected str instance, int found
','.join(None) # 引发 TypeError: can only join an iterable
4.19 str.find()函数
在字符串中查找子串,返回首次出现的索引。
# 基本使用
'hello world'.find('world') # 输出 6
'hello world'.find('o') # 输出 4
# 临界值处理
'hello'.find('x') # 输出 -1(未找到)
''.find('') # 输出 0
'hello'.find('') # 输出 0
'hello'.find(None) # 引发 TypeError: must be str, not NoneType
4.20 str.rfind()函数
从右侧开始查找子串。
# 基本使用
'hello world'.rfind('o') # 输出 7
# 临界值处理
'hello'.rfind('x') # 输出 -1
''.rfind('') # 输出 0
'hello'.rfind('', 10) # 输出 5(超过字符串长度)
4.21 str.replace()函数
替换字符串中的指定子串。
# 基本使用
'hello world'.replace('world', 'Python') # 输出 'hello Python'
# 指定替换次数
'ababab'.replace('a', 'c', 2) # 输出 'cbcbab'
# 临界值处理
'hello'.replace('', '-') # 输出 '-h-e-l-l-o-'
'hello'.replace('x', 'y') # 输出 'hello'(无匹配)
'hello'.replace(None, 'y') # 引发 TypeError: replace() argument 1 must be str, not NoneType
4.22 str.strip()函数
去除字符串两端的空白字符。
# 基本使用
' hello '.strip() # 输出 'hello'
'\thello\n'.strip() # 输出 'hello'
# 指定去除字符
'xxhelloxx'.strip('x') # 输出 'hello'
# 临界值处理
''.strip() # 输出 ''
' '.strip() # 输出 ''
None.strip() # 引发 AttributeError
4.23 str.lstrip()函数
去除字符串左侧的空白字符。
# 基本使用
' hello '.lstrip() # 输出 'hello '
# 临界值处理
''.lstrip() # 输出 ''
None.lstrip() # 引发 AttributeError
4.24 str.rstrip()函数
去除字符串右侧的空白字符。
# 基本使用
' hello '.rstrip() # 输出 ' hello'
# 临界值处理
''.rstrip() # 输出 ''
None.rstrip() # 引发 AttributeError
4.25 str.upper()函数
将字符串转换为大写。
# 基本使用
'Hello'.upper() # 输出 'HELLO'
# 临界值处理
''.upper() # 输出 ''
'123'.upper() # 输出 '123'
None.upper() # 引发 AttributeError
4.26 str.lower()函数
将字符串转换为小写。
# 基本使用
'Hello'.lower() # 输出 'hello'
# 临界值处理
''.lower() # 输出 ''
'123'.lower() # 输出 '123'
None.lower() # 引发 AttributeError
4.27 str.title()函数
将每个单词的首字母大写。
# 基本使用
'hello world'.title() # 输出 'Hello World'
# 临界值处理
''.title() # 输出 ''
"they're bill's".title() # 输出 "They'Re Bill'S"(注意撇号后的字母)
None.title() # 引发 AttributeError
5. 列表操作相关函数
5.28 list.append()函数
在列表末尾添加元素。
# 基本使用
lst = [1, 2]
lst.append(3) # lst变为[1, 2, 3]
# 临界值处理
lst.append(None) # lst变为[1, 2, 3, None]
lst.append(lst) # 可以添加自身(创建循环引用)
5.29 list.extend()函数
用可迭代对象扩展列表。
# 基本使用
lst = [1, 2]
lst.extend([3, 4]) # lst变为[1, 2, 3, 4]
# 临界值处理
lst.extend('abc') # lst变为[1, 2, 3, 4, 'a', 'b', 'c']
lst.extend(None) # 引发 TypeError: 'NoneType' object is not iterable
5.30 list.insert()函数
在指定位置插入元素。
“`python
基本使用
lst = [1, 3]
lst.insert(1, 2) # lst变为[1, 2, 3]
临界值处理
lst.insert(-10, 0) # 插入到最前面
lst.insert(100, 4) # 插入到
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...