Python内置函数的使用及常见操作示例
发布时间:2023-07-03 14:33:28
Python内置函数是Python解释器自带的一些函数,可以直接调用并使用,无需额外导入模块。Python内置函数包括一些常用的数学函数、字符串函数、列表函数、字典函数等。
下面是一些常见的Python内置函数及其示例:
1. 数学函数:
- abs():计算绝对值
num = -10 print(abs(num)) # 输出:10
- round():四舍五入
num = 3.14159 print(round(num, 2)) # 输出:3.14
2. 字符串函数:
- len():返回字符串的长度
str = "Hello, World!" print(len(str)) # 输出:13
- upper():将字符串转换为大写
str = "hello" print(str.upper()) # 输出:HELLO
3. 列表函数:
- len():返回列表的长度
list = [1, 2, 3, 4, 5] print(len(list)) # 输出:5
- append():在列表末尾添加元素
list = [1, 2, 3] list.append(4) print(list) # 输出:[1, 2, 3, 4]
4. 字典函数:
- keys():返回字典中所有的键
dict = {"name": "Alice", "age": 20, "city": "New York"}
print(dict.keys()) # 输出:dict_keys(['name', 'age', 'city'])
- values():返回字典中所有的值
dict = {"name": "Alice", "age": 20, "city": "New York"}
print(dict.values()) # 输出:dict_values(['Alice', 20, 'New York'])
5. 文件函数:
- open():打开文件
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
- write():将内容写入文件
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
除了以上示例之外,Python还提供了许多其他内置函数,如min()、max()、sum()用于数值计算;sorted()、reversed()用于排序和反转列表;type()、isinstance()判断数据类型等等。
使用Python内置函数可以方便地进行各种常见的操作,可以大大提高编程效率。当然,如果要实现更复杂的功能,还需要使用到其他Python模块提供的函数和类。
