513 words
3 minutes
Python Note
2024-09-01

基礎#

雜項#

print("Hello World") # 輸出Hello World
1<2 # True
'foo' in 'foo bar' # yes

字串處理#

len("Hello World")
'Hello World'.count('o') # 2
'Hello World'.replace(' ','\n') # 把字串中的空格換成'換行符號'
'Hello' + 'World' # HelloWorld
'Hello World'.index('World') -> 6 # 找尋索引值

編解碼#

hex(100) -> 0x64
bin(100) -> 0b1100100
oct(100) -> 0o144
0x64 -> 100
ord('a') -> 97
chr(97) -> 'a'
base64.b64encode(b'hello') -> b'aGVsbG8='

數學運算#

1+1 -> 2
4**(1/2)+1/7+2 -> 4.142857142857142
pow(2,10) -> 1024
pow(2,10,5) -> 4
72942 % 7 -> 2

變數類型#

NUM = 4
STR = "Hello World!"
FLOAT = 3.14
LIST = [1,2,3,4,5]
TUPLE = (1,2,3,4,5)
SET = {1,2,3,4,5}
DICT = {"name":"Alice","age":18}
BOOL = True or False

選擇結構(如果…就…否則…)#

a = 10
if a>5:
print("a>5")
elif a==5:
print("a==5")
else:
print("a<5")

重複結構(迴圈)#

condiction = True
while condiction:
do_something()
for i in range(10):
print("i = ", i)
#if i == 5:
# break
# continue

Exception Handling(例外處理)#

a = [1,2,3,4]
try:
print(a[4])
except:
print("something went wrong.")
pass #沒東西

requests#

HTTP Methodrequests Method說明
GETrequests.get(url)向指定資源提出請求,可額外設定params參數字典
POSTrequests.post(url)向指定資源提出請求,可額外設定data參數字典
PUTrequests.put(url)向指定資源提供最新內容,可額外設定data參數字典
DELETErequests.delete(url)請求刪除指定的資源
HEADrequests.head(url)請求提供資源的回應標頭(不含內容)
OPTIONSrequests.options(url)請求伺服器提供資源可用的功能選項
Response 物件說明
url資源的url位址
content回應訊息的內容(bytes)
text回應訊息內容字串(str)
raw原始回應訊息串流(bytes)
status_code回應的狀態(int)
encoding回應訊息的編碼
headers回應訊息的標頭
cookies回應訊息的cookies(dict)
history請求歷史(list)
json()將回應訊息進行JSON解碼後回傳(dict)
rasise_for_status()檢查是否有例外發生,如果有就拋出例外
# 把google首頁的HTML印出來
import requests
r = requests.get('https://www.google.com')
print(r.text)
# 爬取某個網站的json檔案
import requests
url = "某個url"
r = requests.get(url)
json_data = r.json()
print(json_data)
# get cookies
import requests
url = "https://www.instagram.com/"
cookie = {"csrftoken":"QWE8928yhrf8723gr827d348y"} # 這是假的
r = requests.get(url,cookies=cookie)
print(r.text)
# 填入登入帳號密碼
import requests
url = "???"
form = {"uid":"admin","password":"123","btnSubmit":"Login"}
r = requests.post(url,data=form)
print(r.text)

pwntools#

import pwn
io = pwn.process("cmd.exe")
io = pwn.remote("1.2.3.4",8080)
io.send("whoami\n")
io.sendline("whoami")
io.sendafter("password:","superpassword\n")
io.sendlineafter("password:","superpassword")
io.recv(1024,timeout=1)
io.recvline()
io.recvuntil("end")
io.recvlines(2)