欢迎访问宙启技术站
智能推送

Python常见内建函数总结及使用示例

发布时间:2023-06-13 15:23:45

Python作为一种高级编程语言,拥有丰富的内置函数来帮助我们处理数据和实现各种功能。这些内置函数通常是非常基础和常用的函数,能够方便地完成某些任务,并且能够提高编程的效率和质量。下面我们就来看一下Python内置函数常见的几种类型及使用示例。

# 数值计算函数

abs():用于取绝对值

例:

print(abs(-2.5))  # 2.5

round():四舍五入函数

例:

print(round(2.555, 2))  # 2.56

pow():求幂函数

例:

print(pow(2, 3))  # 8

divmod():返回整除和余数,返回值是元组类型

例:

print(divmod(7, 3))  # (2, 1)

# 字符串相关函数

len():返回字符串长度

例:

text = 'hello world'
print(len(text))  # 11

str():将其他类型数据转换成字符串类型

例:

num = 123
print(str(num))  # '123'

upper():将字符串所有字母转换成大写

例:

text = 'hello world'
print(text.upper())  # 'HELLO WORLD'

lower():将字符串所有字母转换成小写

例:

text = 'HELLO WORLD'
print(text.lower())  # 'hello world'

find():查找子字符串并返回其所在位置

例:

text = 'hello world'
print(text.find('world'))  # 6

replace():替换字符串中指定子字符串

例:

text = 'hello world'
print(text.replace('world', 'python'))  # 'hello python'

# 列表相关函数

len():返回列表元素数量

例:

lst = [1, 2, 3, 4, 5]
print(len(lst))  # 5

append():在列表末尾添加元素

例:

lst = [1, 2, 3, 4, 5]
lst.append(6)
print(lst)  # [1, 2, 3, 4, 5, 6]

insert():在指定位置插入元素

例:

lst = [1, 2, 3, 4, 5]
lst.insert(3, 0)
print(lst)  # [1, 2, 3, 0, 4, 5]

remove():移除列表中指定元素

例:

lst = [1, 2, 3, 4, 5]
lst.remove(3)
print(lst)  # [1, 2, 4, 5]

sort():将列表元素排序

例:

lst = [3, 2, 1, 5, 4]
lst.sort()
print(lst)  # [1, 2, 3, 4, 5]

# 字典相关函数

keys():返回字典中所有的键(Key)

例:

d = {'name': 'Mike', 'age': 21, 'gender': 'male'}
print(d.keys())  # dict_keys(['name', 'age', 'gender'])

values():返回字典中所有的值(Value)

例:

d = {'name': 'Mike', 'age': 21, 'gender': 'male'}
print(d.values())  # dict_values(['Mike', 21, 'male'])

items():返回字典中所有的键值对

例:

d = {'name': 'Mike', 'age': 21, 'gender': 'male'}
print(d.items())  # dict_items([('name', 'Mike'), ('age', 21), ('gender', 'male')])

get():根据键获取值,如果键不存在则返回默认值

例:

d = {'name': 'Mike', 'age': 21, 'gender': 'male'}
print(d.get('name', 'not found'))  # 'Mike'
print(d.get('height', 'not found'))  # 'not found'

# 文件相关函数

open():打开文件并返回文件对象

例:

f = open('test.txt', 'w')

read():读取文件内容

例:

f = open('test.txt', 'r')
content = f.read()
print(content)
f.close()

write():写入文件内容

例:

f = open('test.txt', 'w')
f.write('hello world')
f.close()

以上是Python内置函数的常见类型及使用示例,可以看出这些函数是编写Python程序的常见工具。掌握这些函数的用法能够提高编程效率,使编写代码变得更加简单和高效。