Created by CyanHall.com
on 11/12/2020
, Last updated: 03/30/2021.
πΒ Β
Star me if itβs helpful.
πΒ Β
1. Simple HTTP Server
python -m http.server
3. Hello
# -*- coding: utf-8 -*-
# hello.py
import sys
if __name__ == '__main__':
print("Hello ", sys.argv)
5. 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)
7. Runtime Debugger
# pip install pytest
import pytest
pytest.set_trace()
9. String
name = 'Cyanhall'
name[0:4] # 'Cy'
name[-4:] # 'hall'
name.startswith('Cyan') # True
name.endswith('hall') # True
'yan' in name # True, Test string contains
11. List
listA = list()
listA.append('1') # ['1']
listA.pop() # return '1', listA is: []
# Sort list of dictionaries
import operator
list_of_dicts.sort(key=operator.itemgetter('name'))
13. Remove file
import os
os.remove(path_of_file)
15. HTTP requests
import requests
# query string inlcude array
params = {'page': 1, 'include[]': ['field1', 'field2']}
requests.get(url, params)
2. Create virtual environment
python -m venv [venv_name]
source [venv_name]/bin/activate
deactivate
4. Run hello.py
python hello.py world again
6. Datetime
# Convert seconds to hours, minutes and seconds
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')
8. Check exist
data = {'key': 'value'}
hasattr(sys, 'argv') # True
hasattr(data, 'key') # False
'key' in data # True
10. Number
n = 4
pad_n = f'{n:02}' # '04'
12. Loop
# Loop with index
for i, item in enumerate(items):
pass
14. Rename file
import os
os.rename('/path/old_filename.ext', '/path/new_filename.ext')
More