Python核心编程(3.8学习笔记)

目录

基本使用

字符串

字符的使用

列表

斐波那契数列的初始子序列

其他流程的控制语句

数组

set、字典

模块

标准模块

输入输出

错误和异常

标准库简介

标准库简介(2)


基本使用

1. 注释
# this is the first comment
2. 使用number类型
spam = 1
print(spam)
3. 使用raw字符串
path = r"C:\some\name"
print(path)
4. 字符串跨行
option = """Hello,
World"""
print(option)
5. 字符串复制、字符串拼接
print('*'*5 + str(spam) + '*'*5)
6. 相邻的字符串会自动拼接
print('Py'
'thon')
7. 字符串切片
word='Python'
print(word[0])
print(word[5])
print(word[-1])
print(word[0:2])
print(word[1:])
8. 字符串切片后的值无法直接修改,只能重新创建
try:
    word[0]='J'
except BaseException as e:
    print(e)
word2 = 'J' + word[1:]
print(word2)
9. 获取字符串的长度
print(len(word2))

字符串

1. 不存在字符类型
name = 'zhangsan'
if name[0]==name[0:1]:
    print('equal')
2. 打印Bytes类型
name2 = str(b'Zoot!')
print(name2)
3. 使用utf-8转义
name3 = str(b'Zoot!',encoding='utf-8')
print(name3)

字符的使用

1. 首字母大写
>>> s='Python'
>>> s.capitalize()
'Python'
2. 所有字母都转成小写
>>> s.casefold()
'python'
3. 两边扩展字符
>>> s.center(10,'z')
'zzPythonzz'
4. 统计字符出现个数
>>> s.count('y')
1
>>> s.count('y',0,3)
1
6. 字符串编码
>>> s.encode(encoding='ascii')
b'Python'
7. 判断字符串是否以X结尾
>>> s.endswith('n')
True
>>> s.endswith('y',0,2)
True
8. 字符串tab键替换
>>> s='py\tth\non'
>>> s.expandtabs(4)
'py  th\non'
9. 查找字符首次出现位置
>>> s = 'python'
>>> s.find('y',0, 3)
1
10. 判断字符串是否出现(in表达式)
>>> 'py' in s
True
11. 字符串格式化输入
>>> 'The sum of 1+2 is {0}'.format(1+2)
'The sum of 1+2 is 3'
12. 字符串格式化输入(使用dist格式化)
>>> people = {name:'zhangsan',age: 22}
>>> '{name} is age {age}'.format_map(people)
'zhangsan is age 22'
13. 查找字符出现的首位置(没有找到会报出异常)
>>> s = 'python'
>>> s.index('p')
0
14. 判断字符串是否是数字
>>> s='123'
>>> s.isalnum()
True
>>> s.isdigit()
True
>>> s.isdecimal()
True
>>> s.isascii()
True
>>> s.isalpha()
False
15. 判断字符串是否是python关键字
>>> s='class'
>>> s.isidentifier()
True
16. 判断字符串是否都是小写
>>> s.islower()
True
17. 删除前导字符
>>> s='  zhangsan'
>>> s.lstrip()
'zhangsan'
18. 根据字符映射表转换字符
>>> s='abcdefg'
>>> s.translate(str.maketrans('abc','123'))
'123defg'
19. 字符串分割,从前找到第一个字符,然后分成前面、中间、后面三部分
>>> s='zhangsan'
>>> s.partition('a')
('zh', 'a', 'ngsan')
20. 字符串替换
>>> s='zhzhzhzh'
>>> s.replace('zh','sh',2)
'shshzhzh'
21. 字符串从右面查找
>>> s.rfind('zh')
6
22. 字符串从右面查找
>>> s.rindex('zh')
6
23. 字符串补充,让当前的字符串靠右,左面用补充符补充
>>> s='sh'
>>> s.rjust(5,'-')
'---sh'
24. 字符串分割成三部分,从右面开始
>>> s='abccd'
>>> s.rpartition('c')
('abc', 'c', 'd')
25. 去除空格,从右面开始,可以指定任何冗余字符
>>> s='  abc  '
>>> s.rstrip()
'  abc'
>>> 'mississippi'.rstrip('ipz')
'mississ'
26. 字符串分割,指定最多替换个数,默认参数是空格
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',',maxsplit=1)
['1', '2,3']
>>>  '   1   2   3   '.split()
['1', '2', '3']
27. 字符串分割,默认参数是所有不显示字符
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> "One line\n".splitlines()
['One line']
28. 判断字符串是否以……开始
>>> s='one'
>>> s.startswith('on')
True
29. 去除冗余字符,从左右都去除
>>> s='........one...two...'
>>> s.strip('.')
'one...two'
30. 大小写转换
>>> s.swapcase()
'........ONE...TWO...'
31. 转换成标题
>>> s.title()
'........One...Two...'
32. 转化成大写
>>> s.upper()
'........ONE...TWO...'
33. 数字类型的字符前面补充0
>>> "-42".zfill(5)
'-0042'
34. 格式化字符串
>>> name='Fred'
>>> f'He said his name is {name}'
'He said his name is Fred'
>>> age=18
>>> f'{name} is age {age}.'
'Fred is age 18.'
35. 格式化字符串
>>> 'Fred is age {}'.format('18')
'Fred is age 18'
36. printf风格的格式化
>>> print('%(name)s is age %(age)d' % {'name':'zhangsa','age':18})
zhangsa is age 18

列表

1. 使用列表
>>> suq = [1,4,9,16]
>>> suq[0]
1
2. 切片
>>> suq[:]
[1, 4, 9, 16]
3. 拼接
>>> suq + [16,32]
[1, 4, 9, 16, 16, 32]
4. 追加
>>> suq
[1, 4, 9, 16]
>>> suq.append(32)
>>> suq
[1, 4, 9, 16, 32]
5. 切片赋值
>>> letters=['a','b','c','d']
>>> letters[2:4]=['B','C']
>>> letters
['a', 'b', 'B', 'C']
5. 列表数量
>>> len(letters)

斐波那契数列的初始子序列

a,b = 0,1
while a< 10:
    print(a)
    a,b = b, a+b

其他流程的控制语句

# if语句
x = int(input('Please enter an integer'))
if x<0:
    x=0
    print('<0')
elif x==0:
    print('=0')
else:,
    print('>0')
# for语句
word = ['cat','window','defenstrate']
for w in word:
    print(w)
# 在循环中修改数组,先拷贝出一个副本
for w in word[:]:
    if len(w)>6:
        word.insert(0, w)
print(word)
# 使用range函数
for i in range(6):
    print(i)
for i in range(2, 11, 2):
    print(i)
# 将迭代对象转换成列表
l = list(range(5))
print(l)
# for...else,for可以写else语句,这将在for判断失败的时候执行,不过及其不建议这么写
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')
# pass语句
def initLog():
    pass
​
# 定义函数
def hi():
    print('hi')
# 函数可以被赋值
f = hi
f()
​
# 参数默认值
def ask_ok(name='hello'):
    print(name)
​
ask_ok()
ask_ok('hi')
​
# 参数的默认值是在函数定义时计算的
i = 5
def f(arg = i):
    print(arg)
i = 6
f()
# 默认值只会执行一次
def f(a, L=[]):
    L.append(a)
    return L
​
print(f(1))
print(f(2))
print(f(3))
# 关键字参数
def parrot(voltage, state='a stiff'):
    print(voltage, state)
​
parrot('name', state='zhangsa')
​
# 任意的参数列表
def write_items(a,b,*args):
    l = args
    print(l[0],l[1],l[2])
​
write_items(1,2,3,4,5)
​
# lambda表达式
f = lambda x: x+1
print(f(1))
# 文档字符串
def hello(name:str)->str:
    """Hello
    """
    print(name)
    return name
print(hello.__doc__)
# 函数标注
print(hello.__annotations__)

数组

# 扩展一个元素
l = ['apple']
l.append('banana')
print(l)
# 扩展多个元素
l.extend(['zhang','li','wang'])
print(l)
# 在指定位置插入
l.insert(0,'zhao')
print(l)
l.remove('zhao')
# 弹出指定/最后一个元素
last = l.pop()
print(l, last)
# 删除所有元素
l.clear()
s = ['zhang','li']
print('zhang position is ',s.index('zhang'))
# 排序
s.sort()
print(s)
# 倒序
s.reverse()
print(s)
# copy()获取元素的浅拷贝
s.copy().append('wang')
print(s)
# 列表作为栈使用
stack = [3,4,5]
stack.append(6)
last = stack.pop()
# 列表作为队列使用
from collections import deque
queue = deque([1,2,3])
queue.append(4)
first = queue.popleft()
print(first,queue)
# 列表推导式:方式1
squares = list(map(lambda x: x**2, range(10)))
print(squares)
# 方式2
squares = [x**2 for x in range(10)]
print(squares)
s = [(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]
print(s)
# del语句,可以方便的删除切片
a=[1,2,3,4]
del a[2:4]
print(a)

set、字典

# 定义元组
t = 1,2,3,4
print(t)
# 元组可以嵌套
a = t,(5,6,7)
print(a)
empty = ()
print(len(empty))
# 定义集合
basket = {'apple','orange','apple'}
print(basket)
print('apple' in basket)
# 定义字符集合
a = set('abracadabra')
print(a)
# 集合计算
a = set('abcde')
b = set('def')
# 差集
print(a-b)
# 交集
print(a&b)
# 并集
print(a|b)
# 交集取反
print(a^b)
# 使用列表推导式创建集合
a = {x for x in 'abcdefg' if x not in 'cd'}
print(a)
# 创建集合
tel = {'jack':4096,'spce':4128}
# 添加新元素
tel['guido'] = 4127
print(tel)
# 删除元素
del tel['jack']
print(tel)
# 获取key列表
print('list',list(tel))
# 对key排序
print('sort',sorted(tel))
# 判断key是否存在
print('guido' in tel)
# 从键值对序列中创建字典
print(dict([('a', 1), ('c', 2), ('b', 3)]))
# 从推导式中创建字典
print({x:x**2 for x in (2,4,6)})
# 通过参数指定创建字典
print(dict(zhangsan=123,lisi=234,wangwu=345))
# 字典遍历
a = dict(a=1,b=2,c=3)
# for k,v in a.items():
#     print(k,v)
for i,v in enumerate(a):
    print(i,v)
# zip可以讲两个list组合成一个map
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q,a in zip(questions,answers):
    print('what is your {0}? it is {1}'.format(q,a))
​
# 逆向遍历
for i in reversed(range(5)):
    print(i)
# 遍历排序数组
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for i in sorted(set(basket)):
    print(i)
​
# in&not in&is&not is
print('a' not in 'bcd')
a,b = 'a','a'
# is用来判断对象是否是同一个对象
print(a is b)
c,d = {'a'},{'a'}
print('c is d',c is d)
print('c==d',c == d)
​
# and&or短路运算符
a = 3
if a<5 or a!=3:
    print('a<5 or a!=3')
​
# 序列的比较(按照顺序比较)
if (1,2,3) < (3,2,1):
    print('<')
else:
    print('>=')

模块

  1. 先创建一个文件fibo.py

    def fib(n):
        a,b = 0,1
        while a<n:
            print(a,end=' ')
            a,b = b, a+b

     

  2. 在另一个文件中引入

    import fibo
    fibo.fib(10)
    print(fibo.__name__)

     

  3. 在另一个模块中直接导入函数

    from fibo import fib
    fib(100)

     

  4. 如果希望导入模块中的所有内容,可以使用

    from fibo import *
    fib(10)

     

  5. 可以对导入的函数重新命名

    from fibo import fib as fibrename
    fibrename(100)

     

标准模块

import fibo, sys
# 读取python解释器搜素模块路径
print(sys.path)
# dir函数,列出所有导出符号的名称
print(dir(fibo))
print(dir(sys))

  1. 创建一个包

    \fibonum
    
    \fibonum\init.py(init前后有两个下划线),空文件
    
    \fibonum\fibo.py
    
    \index.py

     

  2. 导入包

from fibonum.fibo import fib
fib(100)
  1. 导入父包

    from . import echo
    from .. import formats
    from ..filters import equalizer

     

输入输出

# 格式化字符串(1)
name = 'zhangsna'
age = 21
print(f'{name} is age {age}')
# repr生成解释器可以返回的值
s = 'hello world'
print(repr(s))
# 格式化字符串(2)
print('{} is age {}'.format(name,age))
print('{0} is age {1}'.format(name,age))
print('{0} is age {1:4d}'.format(name,age))
print('12'.zfill(5))
# 正常打开文件
f = open('a.txt','w')
f.write('Hello world')
f.close()
# 使用with,不需要close
with open('b.txt', 'w') as f:
    f.write('hello world')
print(f.closed) #True
​
with open('b.txt','r') as f:
    print(f.read())
    # 读取一行
    print(f.readline())
    # 读取所有行,保存在列表中
    print(f.readlines())
    print(list(f))
​
with open('c.txt','ab') as f:
    # 写入文件
    f.write(b'hello world')
    # 返回从文件开始的字节数
    print('f.tell()',f.tell())
​
with open('c.txt','rb+') as f:
    f.write(b'0123456789')
    f.seek(5)
    print(f.read(1))
    # 0表示开始,1表示当前,2表示结尾
    f.seek(-3,2)
    print(f.read(1))
​
# 使用json保存数据结构
import json
print(json.dumps([1,'simple','list']))
strJson = json.dumps({
    'name':'zhang',
    'age': 21,
    'data':{
        'like':[
            'pingpang',
            'basketball'
        ]
    }
})
print(strJson)
jsonObj = json.loads(strJson)
print(jsonObj['name'])
print(jsonObj['data']['like'][0])

错误和异常

# 检查异常
try:
    10/0
except Exception as e:
    print(e)
# 抛出异常
x=input('please input a number')
try:
    nX = int(x)
    if(nX == 0):
        raise Exception('输入的数字不能为0')
    print('倒数:',1/nX)
except Exception as err:
    print(err)
# 清理工作
try:
    raise Exception('程序抛出异常')
except Exception as err:
    print(err)
finally:
    print('程序正在退出')
​
​

#  在def中再定义def,类似于类的概念,def区别全局变量和局部变量使用global
def scope_test():
    def make_global():
        global a
        a = "bbb"
​
    a = "aaa"
    make_global()
​
scope_test()
print(a)
​
class people:
    name = 'zhangsan'
    def __init__(self):
        print('Create')
    
    def sayHi(self):
        print('{} say hi'.format(self.name))
# 创建对象
p = people()
p.sayHi()
# 属性可以直接被调用
print(p.name)
# 方法可以被保存
f = p.sayHi
f()
​
class Dog:
    # 每一个成员变量都需要被初始化
    kind = ''
    def __init__(self, kind):
        self.kind = kind
        # 可以直接给self对象添加新的值
        self.name = 'MyDog'
    
    def say(self):
        print(self.name)
​
d = Dog('Dog')
d.say()
print(d.kind)
​
# 函数不是一定要定义在class内部
def f1(self, x, y):
    return min(x,y)
​
class C:
    f = f1
    def g(self, x, y):
        return self.f(x,y)
​
c = C()
print('g',c.g(1,2))
​
# 继承
class A:
    name = 'name'
    def __init__(self):
        print('A Create')
    
    def sayHi(self):
        print(self.name)
​
class B(A):
    def __init__(self):
        # 使用super获取父类对象
        super(B, self).__init__()
        print('B Create')
​
    # 方法改写
    def sayHi(self):
        print('B',self.name)
​
b = B()
b.sayHi()
​
# 迭代器
for element in [1,2,3]:
    print(element)
# 直接使用迭代器对象
it = iter([1,2,3])
print('0',next(it))
print('1',next(it))
# 创建具有迭代器兑现的类
class C:
    data = ['zhangsan','lisi','wangwu']
    index = -1
    def __init__(self):
        pass
​
    def __iter__(self):
        return self
    
    def __next__(self):
        self.index = self.index+1
        if(self.index == 3):
            raise StopIteration
        return self.data[self.index]
​
c = C()
for item in c:
    print(item)
​
# 生成器,自动创建__next__和__iter__方法
def getchar():
    for i in 'apple':
        yield i
​
for c in getchar():
    print(c) 
# 生成器表达式
print(sum(i*i for i in range(10)))
​
​

标准库简介

import os
# 获取路径
print(os.getcwd())
# 修改当前执行路径
# print(os.chdir('./'))
os.system('notepad')
# 文件操作
import shutil
shutil.copyfile('c.txt','d.txt')
shutil.move('c.txt','e.txt')
# 文件通配符查找
import glob
print(glob.glob('*.txt'))
# 命令行参数
import sys
print(sys.argv)
# 错误输出重定向程序终止
import sys
sys.stderr.write('Error')
sys.exit()
# 字符串模式匹配
import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest'))
import math
print(math.cos(math.pi/4))
# 从列表中随机选择1个
import random
print(random.choice(['apple','pear','banban']))
# 从列表中随机抽出10个
print(random.sample(range(100), 10))
# 从range(10)中随机抽出
print(random.randrange(10))
# 计算中位数、平均值、方差等
import statistics
data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
print(statistics.mean(data))
​
# 互联网访问
from urllib.request import urlopen
with urlopen('http://www.baidu.com') as response:
    for line in response:
        line = line.decode('utf-8')
        print(line)
​
#  日期和时间
from datetime import date
now = date.today()
print(now)
# 格式化输出
print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B."))
# 计算时间差
birthday = date(1964, 7, 31)
print((now - birthday).days)
​
# 压缩&解压
import zlib
s = b'witch which has which witches wrist watch'
print(s,len(s))
t = zlib.compress(s)
print(t,len(t))
print(zlib.decompress(t))
​
#  测试
def average(values):
    """
    >>> print(average([20, 30, 70]))
    30.0
    """
    return sum(values) / len(values)
​
import doctest
print(doctest.testmod())
​

​

标准库简介(2)
 

# 用于缩略显示大类型对象
import reprlib
print(reprlib.repr(set('supercalifragilisticexpialidocious')))
# 模板
from string import Template
t = Template('$village folk send $$10 to $cause.')
print(t.substitute(village='Nottingham', cause = 'the ditch fund'))
​
# 使用二进制数据记录格式,见struct提供的方法pack和unpack
# 多线程
import threading, zipfile
class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile
​
    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)
​
background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')
​
background.join()    # Wait for the background task to finish
print('Main program waited until background was done.')
​
# 日志
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
# 弱引用 可以使用weakref手动管理GC
# 用于列表的对象
from array import array
a = array('H',[4000, 10, 700, 22222])
print(sum(a))
# 队列
from collections import deque
d = deque(['task1','task2','task3'])
d.append('Handle')
print(d.popleft())
# 排序列表
import bisect
scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
bisect.insort(scores, (300, 'ruby'))
print(scores)
# 堆
from heapq import heapify, heappop, heappush
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data)
heappush(data, -5)
print([heappop(data) for i in range(3)])
# 用于精度高的场合
from decimal import *
print(Decimal('1.00') % Decimal('.10'))
print(1.00%0.10)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值