Python常用库函数使用方法
Python是一种高级编程语言,它拥有非常丰富的标准库和第三方库。这些库为Python开发者提供了丰富的工具和函数,可以大大提高编程效率。本文将介绍Python常用库函数的使用方法,方便Python初学者快速入门。
一、os库
os模块是Python中一个非常常用的模块,该模块提供了一种方便的访问操作系统功能的方式。我们可以使用os模块来操作文件和目录、管理进程、操作系统信息等。
常用方法:
1.os.getcwd(): 获取当前工作目录
2.os.chdir(path): 改变当前工作目录
3.os.listdir(path): 列出指定目录下所有文件和子目录
4.os.path.split(path): 拆分path成两个部分(目录与文件名)
5.os.path.join(path1, path2): 将两个路径组合起来,如path1='/usr',path2='local/bin'则结果为'/usr/local/bin'
6.os.path.exists(path): 判断路径存在与否,返回True或False。
举个例子:
import os
print(os.getcwd()) #获取当前工作目录
os.chdir("/test") #将当前工作目录改为/test
print(os.getcwd()) #打印/test
print(os.listdir(os.getcwd())) #打印出/test目录下所有的文件和子目录
二、time库
time模块提供了与时间相关的函数,包括获取当前时间、操作时间戳、格式化时间等功能。
常用方法:
1.time.time(): 返回当前时间戳
2.time.localtime(seconds): 将指定的时间戳转换为本地时间
3.time.sleep(seconds): 程序暂停制定秒数
4.time.strftime(format_str, time_tuple): 将时间元组格式化为指定格式的字符串
5.time.strptime(time_str, format_str): 将字符串解析为时间元组
举个例子:
import time
print(time.time()) #打印当前时间戳
print(time.localtime(time.time())) #将时间戳转换为本地时间
time.sleep(2) #程序暂停2s
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) #格式化时间为指定格式的字符串
三、math库
math模块提供了常用的数学函数,包括幂函数、对数函数、三角函数等等。
常用方法:
1.math.sqrt(num): 开平方
2.math.pow(num, exp): 指数运算
3.math.sin(num): 正弦值
4.math.cos(num): 余弦值
5.math.tan(num):正切值
6.math.ceil(num): 向上取整
7.math.floor(num): 向下取整
8.math.pi: 数学常量π
举个例子:
import math
print(math.sqrt(16)) #开平方
print(math.pow(2, 3)) #2的3次方
print(math.sin(math.pi/6)) #30度的正弦值
print(math.cos(math.pi/6)) #30度的余弦值
print(math.tan(math.pi/6)) #30度的正切值
print(math.ceil(5.6)) #向上取整
print(math.floor(5.6)) #向下取整
四、random库
random模块提供了与随机数相关的函数,包括生成随机数、打乱序列等等。
常用方法:
1.random.random(): 生成一个随机的小数
2.random.randint(a, b): 生成一个[a,b]之间的整数
3.random.choice(sequence): 从序列中随机选择一个元素
4.random.shuffle(sequence): 随机打乱序列
5.random.sample(sequence, k): 从序列中随机选择k个元素
举个例子:
import random
print(random.random()) #生成随机小数
print(random.randint(1, 10)) #生成1-10之间的整数
print(random.choice(["apple", "banana", "orange"])) #从序列中随机选择一个元素
seq = [1,2,3,4,5]
random.shuffle(seq)
print(seq) #打乱序列
print(random.sample(seq, 3)) #从序列中随机选择3个元素
五、re库
re模块提供了正则表达式的支持,常用于字符串的匹配和查找等操作。
常用方法:
1.re.match(pattern, string): 从字符串开头开始匹配正则表达式
2.re.search(pattern, string): 从整个字符串中查找 个匹配的子串
3.re.findall(pattern, string): 在整个字符串中查找所有匹配的子串,并返回一个列表
4.re.sub(pattern, repl, string): 将字符串中所有匹配正则表达式的子串都替换成指定的字符串
举个例子:
import re
string = "apple is delicious"
pattern = "apple"
match_obj = re.match(pattern, string)
if match_obj:
print(match_obj.group()) #匹配成功,打印匹配到的子串
else:
print("Match failed")
search_obj = re.search(pattern, string)
if search_obj:
print(search_obj.group()) #查找 个匹配的子串
else:
print("Search failed")
pattern = "\w+"
print(re.findall(pattern, string)) #查找所有匹配的子串
pattern = "apple"
repl_str = "orange"
new_string = re.sub(pattern, repl_str, string)
print(new_string) #替换掉所有匹配的字符串
以上是Python常用库函数的使用方法,这些函数是Python编程中非常重要的部分,熟练掌握这些函数可以大幅提高编程效率,接下来就让我们用起来吧!
