Python基础笔记

字数 998 · 2018-04-03

#python

数据类型

String

String Interpolation

1
2
3
name = 'Ray'
print(f'Hello, {name}!')
# >> Hello, Ray!

运算

python中没有++,--,但是有i+=1

布尔运算

没有Java里的 &&, ||, !,取而代之的是 and,or, not

1
2
3
x or y
x and y
not x

三目运算

ternary

没有其他语言里的 ?: 运算符。

1
a if condition else b

函数式编程

Built-in
map filter enumerate sorted zip any all

functools
reduce

包和模块

包是含有__init__.py的文件夹。
一个文件就是一个模块,模块由代码,函数和类组成。
a moudle is a file containing Python definitions and statements.

正则表达式

使用 r 前缀( raw string ),忽略转义

1
2
3
4
5
6
7
8
9
import re
# 匹配成功返回Match对象,否则返回None
re.match(pattern, string)
# 以pattern分割字符串
re.split(pattern, string)
# 返回所有匹配的字符串
re.findall(pattern, string)
# 返回第一个匹配的字符串
re.search(pattern, string)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a = re.match(r'.*?(\d+)','asda2131')
# group(0)为原始字符串
a.group(0)
>>> 'asda2131'
a.group(1)
>>> '2131'
re.split(r'\s','a   b    c')
>>> ['a', 'b', 'c']
'a b    c'.split(' ')
>>> ['a', 'b', '', '', 'c']
re.findall(r'\d+','a1213b343c4324d1.233e5')
>>>['1213', '343', '4324', '1', '233', '5']
re.findall(r'([a-z]+)(\d+)','a1213b343c4324d1.233e5')
# 返回的是元组列表
>>>[('a', '1213'), ('b', '343'), ('c', '4324'), ('d', '1'), ('e', '5')]

正向预查, 这是一个非获取匹配,意思是不需要获取供后面使用, 也不消耗字符.
(?=xxx) - Positive lookaround , Matchs a group after the main expression without including it in the result.

使用 (?P<group name>) 给组别命名, 使用 (?P=group name) 来使用

1
2
3
re.match(r'(?P<g1>\d+)abc(?P=g1)','123abc123')
# 这么写还比较简单...
re.match(r'(\d+)abc\1','123abc123')

re.M / re.MULTILINE

When specified, the pattern character '^' matches at the begining of the string and at the begining of each line;
and the pattern character '$' matches at the end of the string and at the end of each line.
By default, '^' matches only at the begining of the string, and '$' only at the end of string.

re.S / re.DOTALL

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

时间

1
2
3
import time
time.strftime('%Y-%m-%d %H:%M:%S')
# 当前时间

IO操作

读取json

1
2
3
4
5
6
7
import json
# 从文件中
json.load(open('file.json','r'))
# 从String中
json.loads('string')
# 导出文件,ensure_ascii=False用于导出中文字符而不是\uxxxx
json.dump( obj,fp,ensure_ascii=False )

URL编码

1
2
3
4
5
6
import urllib
urllib.parse.quote('==')
>>> '%3D%3D'
urllib.parse.unquote('%3D%3D')
>>> '=='

Base64

1
2
3
4
5
import base64
base64.b64encode('你好'.encode())
>>> b'5L2g5aW9'
base64.b64decode('5L2g5aW9').decode()
>>> '你好'

MD5

1
2
3
import hashlib
hashlib.md5('dig str'.encode()).hexdigest()
#> 'da30ced553e3ca363f1897b250ddf29b'

OPENSSL 版本

1
2
import ssl
ssl.OPENSSL_VERSION

One Line Server

1
python -m http.server 8000

os.system

1
2
import os
os.system('git checkout master')

shebang

PATH 中查找 python3

1
#!/usr/bin/env python3

Concurrency

Python Concurrency.pdf - PyCon

requirements.txt

generate requirements.txt file for the particular project:

1
2
pip install pipreqs
pipreqs