Python函数中常用的内置函数及其使用
Python内置函数是Python解释器中已经定义好的函数,用户无需再次定义就可以直接使用。这些函数包括常见的数学函数、字符串函数、列表函数、字典函数、文件操作函数等。在Python编程中,这些内置函数可以帮助我们提高代码的效率,同时也减少了编程的工作量。下面介绍Python中常用的内置函数及其使用方法。
1.类型判断函数:type()
type(obj)函数返回obj的类型,可以用于判断一个对象的类型。例如:
a = 10
b = "hello"
c = [1, 2, 3]
print(type(a)) # 输出 <class 'int'>
print(type(b)) # 输出 <class 'str'>
print(type(c)) # 输出 <class 'list'>
2.转换类型函数:int(), float(), str(), list(), tuple(), dict(), set()
这些函数可以将数据类型进行转换,例如将数值类型转换为字符串类型,将列表类型转换为元组类型等。例如:
a = "123"
b = int(a)
c = float(b)
d = str(c)
e = [1, 2, 3]
f = tuple(e)
g = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
h = set(e)
print(b, c, d) # 输出 123 123.0 123.0
print(f) # 输出 (1, 2, 3)
print(g) # 输出 {'a': 1, 'b': 2, 'c': 3}
print(h) # 输出 {1, 2, 3}
3.数学函数:abs(), pow(), round(), divmod()
数学函数可用于常规数学计算。例如:
a = -3
b = abs(a)
c = pow(2, 3)
d = round(3.14159, 2)
e,f = divmod(10, 3)
print(b) # 输出 3
print(c) # 输出 8
print(d) # 输出 3.14
print(e, f) # 输出 3 1
4.字符串函数:len(), str.strip(), str.split(), str.join()
字符串函数可用于常规字符串操作。例如:
a = ' hello '
b = len(a)
c = a.strip()
d = a.split()
e = '-'.join(d)
print(b) # 输出 7
print(c) # 输出 'hello'
print(d) # 输出 ['hello']
print(e) # 输出 'hello'
5.列表函数:len(), max(), min(), list.append()
列表函数可用于列表的操作。例如:
a = [1, 2, 3, 4]
b = len(a)
c = max(a)
d = min(a)
a.append(5)
print(b) # 输出 4
print(c) # 输出 4
print(d) # 输出 1
print(a) # 输出 [1, 2, 3, 4, 5]
6.字典函数:len(), dict.keys(), dict.values(), dict.items()
字典函数可用于字典的操作。例如:
a = {'a': 1, 'b': 2, 'c': 3}
b = len(a)
c = a.keys()
d = a.values()
e = a.items()
print(b) # 输出 3
print(c) # 输出 dict_keys(['a', 'b', 'c'])
print(d) # 输出 dict_values([1, 2, 3])
print(e) # 输出 dict_items([('a', 1), ('b', 2), ('c', 3)])
7.文件操作函数:open(), f.read(), f.write(), f.close()
文件操作函数可用于打开、读取和写入文件。例如:
f = open('file.txt', 'w')
f.write('Hello, world!')
f.close()
f = open('file.txt', 'r')
s = f.read()
f.close()
print(s) # 输出 'Hello, world!'
这些Python内置函数是在编程中经常使用的,可以有效地提高编程效率,可以在Python官方文档中查看其它内置函数的使用方法。
