《Python 常用代码片段》
1. 带索引遍历列表
names = ["jack", "andy", "lucy"]
for idx, val in enumerate(names):
print(idx, val)
输出:
(0, 'jack')
(1, 'andy')
(2, 'lucy')
2. 打印对象/优雅输出
from pprint import pprint
import requests
res = requests.get("https://example.com")
pprint(vars(res))
print(res.status_code)
3. 遍历列表
# Using for loop
lists = [1, 3, 5, 7, 9]
for i in lists:
print(i)
4. 真假判断
Python 中空字符串 ""、数字 0、空列表 [] 均视为假(FALSE):
zero = 0
if zero:
print("zero does not mean FALSE")
else:
print("zero means FALSE")
5. 写中文到文件指定 utf-8 编码
#!/usr/bin/python3
s = '中文'
f = open('test.txt', 'w', encoding='utf8')
f.write(s)
f.close()
阅读 —
·
全站 —