Python 的常见函数总结攻略如下。
1. Python 函数概述
Python 内置了很多常用的函数,可以简化程序代码的编写和命令行交互的操作。常见的 Python 函数包括:
- 数学函数(如 abs, round, pow)
- 字符串函数(如 join, split, replace)
- 列表函数(如 append, pop, count)
- 字典函数(如 keys, values, items)
- 文件处理函数(如 open, read, write)
2. 数学函数
2.1 abs 函数
abs
函数返回一个数的绝对值。
a = -1
b = abs(a)
print(b) # 输出结果为 1
2.2 round 函数
round
函数接受两个参数,第一个参数是需要进行近似操作的浮点数,第二个参数为近似到几位小数,默认是近似到整数位。
a = 3.1415926
b = round(a, 2)
print(b) # 输出结果为 3.14
3. 字符串函数
3.1 join 函数
join
函数将一个序列中的元素以指定的字符进行连接。常用于将多个字符串连接成一个字符串输出。
lst = ['hello', 'world', 'python']
s = '-'.join(lst)
print(s) # 输出结果为 hello-world-python
3.2 split 函数
split
函数是 join
函数的逆操作,它将一个字符串按照指定的字符进行切割,返回一个由多个子串组成的列表。
s = 'hello-world-python'
lst = s.split('-')
print(lst) # 输出结果为 ['hello', 'world', 'python']
4. 列表函数
4.1 append 函数
append
函数可以向列表中添加一个元素。
lst = ['hello', 'world']
lst.append('python')
print(lst) # 输出结果为 ['hello', 'world', 'python']
4.2 pop 函数
pop
函数将列表中最后一个元素弹出,并返回该元素。
lst = ['hello', 'world', 'python']
s = lst.pop()
print(s) # 输出结果为 python
print(lst) # 输出结果为 ['hello', 'world']
5. 字典函数
5.1 keys 函数
keys
函数可以返回字典中所有的键。
d = {'name': 'Python', 'version': '3.7'}
lst = d.keys()
print(lst) # 输出结果为 ['name', 'version']
5.2 values 函数
values
函数可以返回字典中所有的值。
d = {'name': 'Python', 'version': '3.7'}
lst = d.values()
print(lst) # 输出结果为 ['Python', '3.7']
6. 文件处理函数
6.1 open 函数
open
函数可以打开一个文件,并返回文件对象。该函数接受两个参数,第一个参数为文件路径,第二个参数为打开文件的方式(读取方式、写入方式、追加方式等)。
f = open('example.txt', 'w')
f.write('hello world')
f.close()
6.2 read 函数
read
函数可以读取文件中的内容,并返回一个字符串。
f = open('example.txt', 'r')
s = f.read()
print(s) # 输出结果为 hello world
f.close()
以上就是 Python 常见函数的一个摘要,包括数值、字符串、列表、字典和文件处理等。对于更详细的函数使用,可以查看 Python 官方文档。