Python学习_内置函数

时间:2019-03-21
本文章向大家介绍Python学习_内置函数,主要包括Python学习_内置函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

基本内置函数:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

# abs()绝对值
i = abs(-123)
print(i)

# all()循环参数,如果每个元素都为真,那么all的返回值为真
# 假:0,None,"",[],(),{}
r = all([True, True, False])
print(r)

# any()循环参数,如果有一个参数为真,那么any的返回值为真
a = any([True, False, False])
print(a)


# ascii(), 在对象的类里面找 __repr__,获取其返回值
class Foo:
    def __repr__(self):
        return "hello"


obj = Foo()
r = ascii(obj)
print(r)

# bin() 二进制
# oct() 八进制
# int() 十进制
# hex() 十六进制
r = bin(11)
print(r)  # 0b1011,0b表示2进制
r = oct(8)
print(r)  # 0o10 逢8进1,0o表示8进制
r = hex(14)
print(r)  # 0xe e=14,0x 表示16进制

i = int("0b11", base=2)
i = int("0o11", base=8)
i = int("0x11", base=16)
print(i)

# bool() 判断真假或者把一个对象转为布尔值

# bytes() 把字符串转换成字节
bytes("xxx", encoding="utf-8")
# bytearray() 字节列表

# chr() 接收一个数字,找到对应的ascii 码对应的字符
# ord() 将一个字符转为数字,与chr()相反
# 以上2个方法只适用于 ascii 码

# 一个字节是8位 2**8 , 256种
i = chr(65)
print(i)
i = ord("a")
print(i)

# 验证码,ascii 里面对应65-90
# 1.生成65-90的随机数
# 2.把随机数转换成字母 chr(num)
import random

temp = ""
for i in range(6):
    n = random.randrange(0, 4)
    if n == 3 or n == 1:
        rad2 = random.randrange(0, 10)
        temp += str(rad2)
    else:
        # 大于等于65,小于等于91
        rad1 = random.randrange(65, 91)
        c = chr(rad1)
        temp += c
print(temp)


# callable() 判断对象是否可执行
def f1():
    return 123


# f1不能加()
r = callable(f1)
print(r)

# compile() 编译成python可执行的代码
# dir() 列出类下面的所有方法名,help()获取详细的
print(dir(str))

# divmod() 得到商和余数,做页签可以用到此函数
r = divmod(101, 20)
print(r[0], r[1])

# eval() 执行一个字符串表达式,并返回表达式的值
a = "1 + 3"
print(a)
r = eval("1+3")
r = eval("a + 60", {"a": 99})
print(r)

# exec() 直接执行字符串代码,没有返回值
exec("for i in range(5):print(i)")


# filter(函数,可迭代的对象),用于筛选,不能加工元素
# 筛选,循环可迭代的对象,将获取每一个参数,函数(参数)
def f1(x):
    # if x > 22:
    #     return True
    # else:
    #     return False
    return x > 22


# ret = filter(f1, [11, 22, 33, 44])
ret = filter(lambda x: x + 22, [11, 22, 33, 44])
for i in ret:
    print(i)


# map(函数,可迭代的对象,用于加工,对元素进行处理)
def f1(x):
    return x + 100


# ret = map(f1,[1,2,3,4,5])
ret = map(lambda x: x + 100 if x % 2 == 1 else x, [1, 2, 3, 4, 5])
for i in ret:
    print(i)

# filter() 只筛选范围, map()只判断或者改变值,无法筛选
li = [11, 22, 33, 44, 55, 66]
ret = filter(lambda a: a + 33, li)
print(list(ret))

ret2 = map(lambda a: a + 33, li)
print(list(ret2))

# globals() 获取当前代码里面的所有全局变量
# locals()  获取当前代码里面的所有局部变量

# hash("xxxxxxxx") 将字符串改变为hash值,将key优化,方便查找和节省内存

# isinstance(对象,类型) 判断某个对象是否由某个类创建的
# issubclass(class,classinfo) 判断参数 class 是否是类型参数 classinfo 的子类
li = [11, 22]
r = isinstance(li, list)
print(r)

# iter() 创建可迭代的对象,使用next()取下一个值
obj = iter([11, 22, 33, 44])
print(next(obj), next(obj))

# max() 取最大值
# min() 取最小值
li = [11, 22, 33, 44]
print(max(li))
print(min(li))

# pow() 取指数
print(pow(2, 10))

repr() == ascii()

# round() 四舍五入
print(round(3.3))

# sum() 求和
print(sum([11, 22, 33]))

# super() 调用超类的方法
# vars() 函数返回对象object的属性和属性值的字典对象

# zip() 合并为(11, '2'),(22, 'a')
li1 = [11, 22, 33, 44]
li2 = ["2", "a", "bb", "CC"]

r = zip(li1, li2)
for i in r:
    print(i)

__import__()
r = __import__("random")
print(r.randrange(1, 5))

li = [1, 211, 22, 33, 44, 13]
# li.sort() 只能同类型
li.sort()
print(li)
new_li = sorted(li)
print(new_li)

char = ["223", "z", "B", "A", "", "", "", "11", "5", "999", "alex", "_", "a肖"]
new_char = sorted(char)
print(new_char)
for i in new_char:
    print(bytes(i, encoding="utf-8"))

重要内置函数open():

# !/usr/bin/env python
# -*- coding:utf-8 -*-

# 1.打开文件
# 2.操作文件
# 3.关闭文件

# open(文件名,模式,编码)
# 默认只读
f = open("hello.log","r")
# data = f.read()
# f.close()
# print(data)
# print(type(data))

# 基本的打开方式
# r,只读,不存在报错
f = open("hello.log","r")
f.write("guolei")
f.close()

# w,只写,不可读,不存在就创建,存在就清空内容
f = open("hello1.log","w")
f.write("hhhhhh")
f.close()

# x,只写,不可读,不存在就创建,存在就报错
f = open("hello1.log","x")
f.write("456")
f.close()

# a,追加,不可读,不存在就创建,存在就追加内容
f = open("hello1.log","a")
f.write("456")
f.close()

f = open("hello1.log","r",encoding="utf-8")
data = f.read()
print(bytes(data,encoding="utf-8"))
for i in bytes(data,encoding="utf-8"):
    print(i)
f.close()

# 以字节的方式打开,不需要增加encoding参数
# 1.只读,rb
f = open("hello1.log","rb")
data = f.read()
f.close()
print(data)
print(type(data))

# 2.只写,wb
f = open("hello1.log","wb")
f.write(bytes("中国",encoding="utf-8"))
print(f.tell())
f.seek(0)
print(str(f.read(),encoding="utf-8"))
f.close()

# r/w/x/a       => 字符串
# rb/wb/xb/ab   => 字节类型

# + 表示可以同时读写
# r+ 从头开始读,指针默认为0
f = open("hello1.log","r+",encoding="utf-8")
# 不带b,3表示字符,带b,表示字节
data = f.read()
print(type(data),data)
# 文件写入后指针为在末尾
f.write("测试1")
# seek()调整指针的位置,指针为0,表示起始位置
# f.seek(0)
# tell()查看指针位置
print(f.tell())
data = f.read()
print(type(data),data)
f.close()

# w+ , 先清空,再写入,写入之后可以读
f = open("hello1.log","w+",encoding="utf-8")
f.write("测试郭磊")
f.seek(0)
data = f.read()
print(data)
f.close()

# x+ , 跟w+一样,就是文件存在会报错,而w+则清空
f = open("hello1.log","x+",encoding="utf-8")
data = f.read()
print(data)
f.close()

# a+,打开后指针默认在最后面,写的时候,seek无效,永远是追加
f = open("hello1.log","a+",encoding="utf-8")
f.seek(0)
f.write("日本人3")
f.seek(0)
data = f.read()
print(data)
f.close()

# flush()将内存中的数据写入到硬盘(刷新文件内部缓冲区)
# readline() 读取一行
f1 = open("hello1.log","r+",encoding="utf-8")
print(f1.tell())
f1.write("郭磊喜欢夏明吗")
f1.flush()
data1 = f1.read()
print(data1)
f1.seek(0)
data2 = f1.readline()
print(data2)

# truncate() 截取字符串,截取指针到起始位置
f1.seek(9)
f1.truncate()
f1.close()

# 循环读取文件,直到读完所有,每一个循环都是一行数据
f = open("hello1.log", "r", encoding="utf-8")
for line in f:
    print(line)

# 更人性化的close(),Python自动帮你close()
# 自动读取一个文件,并将内容写入到新文件
with open("hello.log", "r", encoding="utf-8") as obj1, open("hello1.log", "w", encoding="utf-8") as obj2:
    for line in obj1:
        obj2.write(line)

# r+可读可写,不会创建不存在的文件。如果直接写文件,则从顶部开始写,
# 覆盖之前此位置的内容,如果先读后写,则会在文件最后追加内容。
# 写入后再次read 则从上次read的地方开始,而不是从文件末尾开始
# (此时貌似与指针没关系,可能有2个指针,不是同一个)
f = open("hello1.log", "r+", encoding="utf-8")
data = f.read(1)
print(f.tell())
print(data)
f.write("郭磊222")
print(f.tell())
print(f.read())
f.close()