您的位置:首页 > 编程语言 > Python开发

Python学习总结二:基本知识点总结

2018-01-01 21:22 615 查看
本人录制技术视频地址:https://edu.csdn.net/lecturer/1899 欢迎观看。

以前有一篇博客介绍过Python的安装环境及基本使用 python学习总结(一)  最近终于有时间继续写自己的技术博客了,也打算将Python系列坚持写下去。这一节打算为大家介绍Python关于字符串及文件的基本操作。
一、字符串操作部分
1. 去除空格
str = ' dwadqwd dwqd '
print(str.strip())
print(str.lstrip())
print(str.rstrip())
2. 字符串连接
s1 = 'AS'
s2 = 'BX'
print(s1 + '\n' + s2)
3. 大小写
str2 = 'abc def'
print(str2.lower())
print(str2.upper())
print(str2.capitalize())
其中capitalize 是首字母大写。
4. 位置比较
str3 = 'abcdef'
str4 = 'addasa'
print(str3.index('bcd'))
try:
print(str4.index('bcc'))
except ValueError:
print('Not Found')

5. 分隔和连接str5 = 'wed,2e3,ass,trr'
result = str5.split(',')
print(type(result))
print(result)
print('-'.join(result))
二、lambda 及相关操作
1. Python中的lambda与C#中的lambda是一个意思,目的都是想使用简明扼要的表达式去表达想要表达的内容,比如计算两个数的和:
sum = lambda arg1, arg2: arg1 + arg2
print('result: %d' % sum(10, 20))
2. map的使用
2.1 数组中的每一个元素加1
l = [1, 2, 3, 4, 5]
new_list = list(map(lambda i: i + 1, l))
print(new_list)
2.2 操作两个数组,将数组对应位置的元素相加,得到新数组
l = [1, 2, 3, 4, 5]
l2 = [4, 5, 6, 7, 8]
new_list = list(map(lambda x, y: x + y, l, l2))
print(new_list)
3. filter的使用,过滤数组中大于3的元素
l = [1, 2, 3, 4, 5]
new_list = list(filter(lambda x: x > 3, l))
print(new_list)
三、装饰器
def hello(fn):
def wrapper():
print('hello, %s' % fn.__name__)
fn()
print('goodboy, %s' % fn.__name__)
return wrapper

@hello
def foo():
print('I am foo')

foo()1)函数foo前面有个@hello的“注解”,hello就是我们前面定义的函数hello

2)在hello函数中,其需要一个fn的参数(这就用来做回调的函数)

3)hello函数中返回了一个inner函数wrapper,这个wrapper函数回调了传进来的fn,并在回调前后加了两条语句。

所以,本质上来讲,用@decorator来装饰某个函数时,其实是做了下面这件事儿:

@decorator
def func():
    pass
变成 
func = decorator(func)
再简单点说,就是把一个函数传到另外一个函数中,再调回给自己。

所以:hello(foo)返回了wrapper()函数,所以,foo其实变成了wrapper的一个变量,而后面的foo()执行其实变成了wrapper()

四、文件操作
1.1  直接写入文件 读取 'input.txt' 文件中的内容,写入 'output.txt' 文件中
file1 = open('input.txt')
file2 = open('output.txt', 'w')

while True:
line = file1.readline()
file2.write(line)
if not line:
break

file1.close()
file2.close()
1.2  第二种方法 文件迭代器,用for循环的方法
file2 = open('output.txt', 'w')
for line in open('input.txt'):
file2.write(line)
2. 序列化与反序列化
2.1 字典的序列化与反序列化
# 序列化
import pickle
d = dict(name = '文宇', age = 18, scroe = 90)
str = pickle.dumps(d)
print(str)

f = open('dump.txt', 'wb')
pickle.dump(d, f)
f.close()

# 反序列化
g = open('dump.txt', 'rb')
h = pickle.load(g)
g.close()
print(h)
2.2  json的序列化与反序列化
import json
str = json.dumps(d)
print(str)

d2 = json.loads(str)
print(d2)

2.3 序列化 & 反序列化对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def detail(self):
print('my name is:%s, my age is %d' % self.name, self.age)

p = Person('Jack', 30)
f11 = open('dump.txt', 'wb')
pickle.dump(p, f11)
f11.close()

g11 = open('dump.txt', 'rb')
h11 = pickle.load(g11)
g.close()
print(h11.name)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息