Python Code Statement / Comment Method

Python Code Statement / Comment Method

dict

default foreach

  • Code
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'} for key in a_dict: print(key)
  • output
color fruit pet

foreach .items()

  • Code
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'} for key in a_dict.items(): print(key)
  • output
('color', 'blue') ('fruit', 'apple') ('pet', 'dog')
  • Code
for key, value in a_dict.items(): print(key, '->', value)
  • Output
color -> blue fruit -> apple pet -> dog

datatime

String(ISO8601) to Datetime

lAt: datetime = dateutil.parser.parse("2019-09-07T-15:50+00")

datetime to ISO8601 String

time=datetime.now() time.isoformat()

JSON

Json String to dict

qobj = json.loads(jstr)

dict to JSON String

jstr = json.dumps(dictObj)

escape unescape

url

import urllib.parse 逃脫後的文字=urllib.parse.quote(jstr) 原文=urllib.parse.unquote(逃脫後的文字)

特殊寫法

range()

for i in range(5): print(i) # out put 0~4 list(range(5)) # [0, 1, 2, 3, 4] range(1, 11) # 从 1 开始到 11 range(0, 30, 5) # 步长为 5 # 0, 5, 10, 15, 20, 25] range(0, -10, -1) # 负数 # [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

List

用 * 重複多個

title = ["H"]*3 # ['H','H','H'] names = ["Andy","Peter","Kirin","Tony"] print(names[-1]) # 取用最後一個 Tony print(names[1:3]) # 去第1位 第2位 不包含 3 Peter Kirin print(names[0:3]) # 去第0位到第2位 不包含 3 Andy Peter Kirin print(names[2:]) # 2位 到最後 Kirin Tony print(names[:]) # 通常用於複製 print(names[::3]) # [0,3,6,9] numbers = list(range(10)) hiNums = [ 'HI:'+ str(n) for n in numbers ] print(hiNums) # ['HI:0', 'HI:1', 'HI:2', 'HI:3', 'HI:4', 'HI:5', 'HI:6', 'HI:7', 'HI:8', 'HI:9']
tags: python
Kirin Note

留言

這個網誌中的熱門文章

angular 如何Http 如何設定 CORS (Cross-Origin Resource Sharing)

Google Map 單車路徑計算坡度和角度小工具

Google URL Shortener API 快速教學