Python中使用的一些常见内置函数和标准库函数,如何使用它们?
发布时间:2023-05-23 14:17:45
Python是一门高级编程语言,它拥有许多内置函数和标准库函数可以用来完成各种任务。这些工具可以帮助我们快速编写出高效且可靠的Python代码。下面我将介绍一些常用的Python内置函数和标准库函数,并附上代码使用样例。
一、内置函数
1. print(): 输出函数,用于向控制台输出一个或多个值。
示例:
print("hello world") # 输出 hello world
print("hello", "world") # 输出 hello world
2. input(): 输入函数,用于从控制台获取用户输入。
示例:
name = input("请输入您的姓名:")
print("您的姓名是:", name)
3. len(): 返回序列的长度。
示例:
s = "hello world" print(len(s)) # 输出 11
4. range(): 返回指定范围内的整数序列。
示例:
print(range(5)) # 输出 range(0, 5) print(list(range(5))) # 输出 [0, 1, 2, 3, 4]
5. format(): 格式化输出函数,用于将变量插入到字符串中。
示例:
name = "Tom"
age = 18
print("我的名字是{},我今年{}岁了。".format(name, age))
6. type(): 返回对象的数据类型。
示例:
s = "hello world" print(type(s)) # 输出 <class 'str'>
二、标准库函数
Python中有许多强大的标准库函数可以用来完成不同的任务,以下是一些常见的标准库函数:
1. math库
math库提供了许多用于数学计算的函数。
示例:
import math a = math.sqrt(4) # 计算平方根 b = math.sin(math.pi / 6) # 计算正弦值 c = math.ceil(5.3) # 向上取整 d = math.floor(5.9) # 向下取整 print(a, b, c, d) # 输出 2.0 0.49999999999999994 6 5
2. random库
用于生成随机数。
示例:
import random a = random.randint(1, 100) # 生成1-100之间的整数 b = random.random() # 生成0-1之间的浮点数 c = random.choice(["apple", "banana", "pear"]) # 随机选择一个元素 d = random.shuffle(["apple", "banana", "pear"]) # 打乱元素顺序 print(a, b, c, d) # 输出一个随机整数、一个随机浮点数、一个随机元素、一个打乱后的列表
3. time库
处理时间相关的函数。
示例:
import time
a = time.time() # 获取当前时间戳
b = time.localtime() # 获取本地时间
c = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 格式化时间
print(a, b, c) # 输出当前时间戳、本地时间、格式化时间
4. re库
用于处理正则表达式。
示例:
import re
s = "apple,banana,pear"
a = re.findall("a\w*", s) # 查找以字母a开头的单词
b = re.sub(",", ";", s) # 将字符串中的逗号替换为分号
c = re.match("apple", s) # 判断字符串是否以apple开头
print(a, b, c) # 输出查找结果、替换后的字符串、是否匹配
以上是一些常见的Python内置函数和标准库函数,它们可以帮助开发者在Python编程中更快地实现程序功能,提高工作效率。
