Python3 零基础自学笔记(一)
基础数学计算
python中拥有与其他语言稍微不同的数学计算表达
[ // ] 除法计算的结果是整数(忽略小数)
>>>17 / 3
5.666666666666667
>>>
>>>17 // 3
5
[ ** ] 计算乘方
>>> 5 ** 2
25
>>> 2 ** 7
128
[ - & ** ]优先级
** 比 - 的优先级更高, 所以 -3 ** 2 会被解释成 - (3 ** 2) ,因此,结果是 -9。要避免这个问题,并且得到 9, 可以用 (-3)**2。
字符串处理
字符串处理中更多聚焦于【 \ 】转义符的处理中
【 \ 】 不代表转义时
如果不希望前置 \ 的字符转义成特殊字符,可以使用 原始字符串,在引号前添加 r 即可
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
字符串跨行连续输入
字符串字面值可以实现跨行连续输入。实现方式是用三引号:"""…""" 或 ‘’’…’’’,字符串行尾会自动加上回车换行,如果不需要回车换行,在行尾添加 \ 即可。示例如下:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
///输出如下(注意,第一行没有换行)
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
索引
Python中索引从0开始
索引支持负数
Python中索引为负,则从右开始计数,且最右端为-1
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
可利用索引进行切片
索引可以提取单个字符,切片 则提取子字符串
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
注意,输出结果包含切片开始,但不包含切片结束。因此,s[:i] + s[i:] 总是等于 s:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
多线程管理
使用 _thread 和 threading 模块进行线程管理
多线程易造成数据混乱错误,需要了解【原语】
创建线程
start_new_thread(function,args.kwargs=None) 派生一个新的线程,使用给定的args和可选的kwargs来执行function
线程加锁
第三方库
测试相关的库
pytest 更加灵活的测试框架库
unitest
requests 网络请求的库
第三方库的安装
pip install 库名
requests 库
>>>import requests
>>>r= requests.get("http://www.baidu.com")
>>>r.status_code
>200
返回200 说明请求成功
>>>r.encoding
>'ISO-8859-1'
返回编码形式
>>>r.text
查看返回结果,如果存在乱码 输入
>>>r.encoding='utf-8'