- Base
- 演算法 Algorithm
- 功能 / Framework
每行不用;
, 使用縮進2格或4格
Comments: #
Docstrings: """ or '''
keywords: https://www.programiz.com/python-programming/keyword-list
內建資料類型:
- boolean : True / False
- int : e.g. 42, 100000
- float : e.g. 3.14159, 1.0e8
- string : 'abc'
- enum
type()
int({str})
LEGB
condition_is_true if condition else condition_is_false
if condition:
pass
if condition:
pass
elif condition:
if condition:
pass
else:
pass
True
True, 'abc', 1, -1, [1,2]
False
False, None, 0, 0.0, '', [], (), {}, set()
python 沒有 替代方式 dictionary
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
- string.ascii_letters
- string.ascii_lowercase
- string.ascii_uppercase
- string.digits
- string.hexdigits
- string.octdigits
str[start : end : step]
len(str)
string to array
str.split(str="", num=string.count(str))
str.rsplit(str="", num=string.count(str))
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
','.join()
- replace:
str.replace(old, new[, max])
default max可指定替換次數 - strip: 預設去除空白
' abcabc '.strip()
- find: 找不到則為-1
str.find(find_str)
- rfind:
str.rfind(find_str)
- count:
str.count(count_str)
- startswith: 字首是不是
str.startswith({word})
- endswith: 字尾是不是
str.endswith({word})
- isalnum: 是否只有英數
str.isalnum()
tools: https://regex101.com/ tutorial: http:https://zwindr.blogspot.com/2016/01/python-regular-expression.html
import re
phone = "123-456-7890"
search = re.search(r'(\d{3})-(\d{3})-(\d{4})', phone)
if search is not None:
pass
search.group(1)..
# re
re.compile(pattern, flags=0)
re.search(pattern, string, flags=0)
re.match(pattern, string, flags=0)
re.split(pattern, string, maxsplit=0, flags=0)
re.sub(pattern, repl, string, count=0, flags=0)
# match
match.group([group1, ...])
pattern = re.compile(r'(\w*) (\w*)(?P<tt>.*)')
match = pattern.match('hello world!!!')
print(match.group(0))
# >> !!!
print(match.group(3))
#同上 >> !!!
print(match.group('tt'))
f = filter(fn, array)
m = map(fn, array)
d = reduce(fn, array)
f = lambda arg1, arg2, ....: expression
class Some:
def __init__(self, x):
self.x = x
@classmethod
def service(clz, y):
print('do service...', clz, y)
Some.service(30)
import datetime
import time
# datetime
now = datetime.datetime.now()
now = datetime.datetime.utcnow()
# timestamp
time.time()
# time tuple
time.localtime()
# date
now.date()
import pytz
now = datetime.datetime.utcnow()
# 從國家取得時區
pytz.country_timezones(‘cn’)
# 取得時區時間
tz = pytz.timezone('Asia/Tokyo')
datetime.datetime.now(tz)
datetime.timedelta
datetime.datetime.now() - datetime.timedelta(days=3)
# 時間差
(datetime.datetime(2015,1,13,12,0,0) - datetime.datetime.now()).total_seconds()
time.strftime("%Y-%m-%d %H:%M:%S")
datetime.datetime.strptime("2014-12-31 18:20:10", "%Y-%m-%d %H:%M:%S")
- json.dumps: dict to json
- json.loads: json to dict
urlparse
from urllib.parse import urlparse
o = urlparse('http:https://www.cwi.nl:80/%7Eguido/Python.html')
o.scheme
o.geturl()
import random
random.randint(0,99) # 隨機整數
random.randrange(0, 101, 2) # 隨機選取0到100間的偶數
random.choice('abcdefg&#%^*f') # 隨機字元
random.sample(range(20), 20)
random.sample('abcdefghij',3) # 多個字元中選取特定數量的字元
random.shuffle([1, 2, 3, 4, 5, 6]) # 洗牌
https://docs.python.org/3/library/csv.html https://blog.gtwang.org/programming/python-csv-file-reading-and-writing-tutorial/