Python 3 速查表

Python 3 速查表

May 28, 2020
速查表
★ 在 GitHub 赞我

Cyanhall 创建.

# 简单 HTTP 服务器
python -m http.server

# 创建虚拟环境
python -m venv [venv_name]
source [venv_name]/bin/activate

# -*- coding: utf-8 -*-
# hello.py
import sys
if __name__ == '__main__':
    print("Hello ", sys.argv)
python hello.py world again
# Hello  ['hello.py', 'world', 'again']

JSON:

import json
jsonStr1 = '{"name":"cyanhall"}'
jsonData = json.loads(jsonStr1)
jsonStr2 = json.dumps(jsonData)
jsonStr2 == jsonStr2 # True
with open('data.txt') as json_file:
    data = json.load(json_file)
with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

Datetime:

# 转换秒数到 时分秒格式
from datetime import datetime, timedelta
str(timedelta(seconds=1000))
# => '0:16:40'

datetime.fromtimestamp(1589990400)
# => datetime.datetime(2020, 5, 21, 0, 0)

now = datetime.now()
# now => datetime.datetime(2020, 5, 28, 20, 38, 16, 389862)
str(now)
# => '2020-05-28 20:38:40.493527'
now.strftime("%Y%m%d %H%M%S")
# => 20200528 203840
now.strftime("%-m/%d")
# => 5/28

# string to datetime
datetime.strptime('2020-06-03T16:17:00+0200', '%Y-%m-%dT%H:%M:%S%z')

# 运行 Debugger: pip install pytest
import pytest
pytest.set_trace()

# 检查是否存在
data = {'key': 'value'}
hasattr(sys, 'argv') # True
hasattr(data, 'key') # False
'key' in data # True

# 字符串
name = 'Cyanhall'
name[0:4] # 'Cy'
name[-4:] # 'hall'
name.startswith('Cyan') # True
name.endswith('hall') # True
'yan' in name # True, 测试字符串是否包含子字符串

# 数字
n = 4
pad_n = f'{n:02}' # '04'

# 列表
listA = list()
listA.append('1') # ['1']
listA.pop() # return '1', listA is: []

# 根据字典的 key 对列表排序
import operator
list_of_dicts.sort(key=operator.itemgetter('name'))

# 移除文件
import os
os.remove(path_of_file)

# 重命名文件
os.rename('/path/old_filename.ext', '/path/new_filename.ext')

HTTP 请求:

import requests

# query string inlcude array
params = {'page': 1, 'include[]': ['field1', 'field2']}
requests.get(url, params)