Python的一些常用函数

本文最后更新于:2 年前

python的一些常用函数

写在前面

因为最近在准备蓝桥杯python组的比赛,特罗列总结出python的一些常用函数。后续随着使用也会陆续整理。

内置函数

1 数学函数

1.1 abs():取绝对值

1
print(abs(-10))  ##10

1.2 divmod():同时取商和余数

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

1.3 sum():求和

1
print(sum[1, 2, 3])  ##6

1.4 round():四舍五入

1
2
print(round(5.1))  ##5
print(round(5.5)) ##6

1.5 pow(m, n):计算m的n次方

1
print(pow(2, 3))  ##8

1.6 min()/max():最小(大)值

1
2
print(min(9, 5, 2, 7))  ##2
print(max(9, 5, 2, 7)) ##9

2 数据转换函数

2.1 hex():十进制转换成十六进制

1
print(hex(100))  ##0x64

2.2 oct():十进制转换成八进制

1
print(oct(100))  ##0o144

2.3 bin():十进制转换成二进制

1
print(bin(100))  ##0b1100100

2.4 bool():将指定参数类型转换成布尔类型

1
print(bool(1))  ##True

2.5 ord():获取单个字符的ASCII数值

1
print(ord("A"))  ##65

2.6 float():转换成浮点数

1
print(float(10))  ##10.0

2.7 chr() :转换一个整数并返回所对应的字符

1
print(chr(65))  ##A

2.8 list(): 将可迭代对象转换为列表

1
print(list(range(1,10)))  ##[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.9 upper()/lower():大小写转换

1
2
3
>>> str = "hELLO world!"
>>> print (str.upper())
HELLO WORLD!

3 对象创建函数

4 迭代器操作函数

基本常用函数

文件操作

1 最基本的文件操作

1
2
3
4
5
6
7
8
fp = open('E:\hello.txt','r')
res = []
s = fp.readlines()
for i in s:
res.append(i.strip('\n')) #使用strip()去掉换行符,如果不去的话会把‘\n’也读进来
fp.close() #记得要关闭连接,养成良好习惯

print(res[:])

2 字符串操作

1
2
3
4
fp =  open('E:\hello.txt','r')
res = [s.strip('\n') for s in fp.readlines()]
fp.close()
print(res[:])

模块

1 datetime模块

1.1 日期对象——date类:

1
2
3
4
import datetimee

d = datetime.date(2019,1,11) # 年,月,日
print(d) ## 2019-01-11
1
2
3
4
5
6
7
8
9
10
11
12
import datetime
a1 = datetime.date(2019,8,26)
print(a1.isocalendar())
print(a1.isoformat())
print(a1.isoweekday())
print(a1.weekday())
print(a1.replace(2018,4,30))
#(2019, 35, 1)
#2019-08-26
#1
#0
#2018-04-30

1.2 时间对象——time类

1
2
3
4
import datetime

t = datetime.time(20, 36, 15, 1) # 时,分,秒,毫秒
print(t) ## 20:36:15.000001

1.3 日期时间对象——datetime类

1
2
3
4
5
6
7
8
9
10
11
12
from datetime import datetime

now = datetime.now()
print('当前日期时间是:',now) ## 2022-03-27 13:45:53.536404
print('当前日期是:',now.date()) ## 2022-03-27
print('当前时间是:',now.time()) ## 13:45:53.536404
```e
日期时间转化为时间戳
```python
from datetime import datetime

print(datetime.now().timestamp()) ##1627700208.446621

时间戳转化为日期时间

1
2
3
from datetime import datetime

print(datetime.fromtimestamp(1627700208.446621)) ## 2022-03-27 13:45:53.536404

日期时间对象转字符串

1
2
3
from datetime import datetime

print(datetime.now().strftime("%Y+%m+%d")) ## 2022+03+27

字符串转日期时间对象

1
2
3
4
5
from datetime import datetime

a = datetime.strptime('2022-5-22 15:23:38', '%Y-%m-%d %H:%M:%S')
print(type(a)) ## <class 'datatime.datatime'>
print(a) ## 2022-5-22 15:23:38

1.4 时间间隔对象——timedelta类

1
2
3
4
5
6
7
import datetime

now = datetime.datetime.now()
a = datetime.timedelta(hours=8,minutes=20,seconds=10)
print(type(a)) ## <class 'datatime.timedelta'>
print(now - a) ## 2021-07-31 02:58:29.424161
print(now + a) ## 2021-07-31 19:38:49.424161

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!