# pyton notes
- 自學python筆記 與 程式紀錄
###### tags: `Python`
## list
### list operate
```python=
myList[start:end:interval]
#not included end
```
:::info
if interval < 0 the list will be upside down
:::
### get index
```python=
idx = myList.index(element)
```
## string
### special string
```python=
#method 1
"%d" % (num)
"%02d" % (num)
#method 2
{}.format(num)
{%02d}.format(num)
#method 3
f"{num}"
f"{num:02d}
```
### join
```python=
S = [s1,s2,s3]
L1 = "_c_".join(S) # L1 -> [s1_c_s2_c_s3]
s.join(map(str, []))
#e.g.
ss = ".".join(map(str,[1,2,3,4]))
#s == "1.2.3.4.5"
```
### zip
```python=
A = [a1,a2,a3]
B = [b1,b2,b3,b4]
C = [c1,c2,c3,c4]
L= [[a1,b1,c1]]
```
### enumerate
```python=
A = [a1,a2,a3]
```
### splat
[*"abc",*"abc"]
###
hex
oct
bin
### muti-line
```python=
a\
=\
3
```
### format
> '<' - Left aligns the result (within the available space)
> '>' - Right aligns the result (within the available space)
> '^' - Center aligns the result (within the available space)
> '=' - Places the sign to the left most position
> '+' - Use a plus sign to indicate if the result is positive or negative
> '-' - Use a minus sign for negative values only
> ' ' - Use a leading space for positive numbers
> ',' - Use a comma as a thousand separator
> '_' - Use a underscore as a thousand separator
> 'b' - Binary format
> 'c' - Converts the value into the corresponding unicode character
> 'd' - Decimal format
> 'e' - Scientific format, with a lower case e
> 'E' - Scientific format, with an upper case E
> 'f' - Fix point number format
> 'F' - Fix point number format, upper case
> 'g' - General format
> 'G' - General format (using a upper case E for scientific notations)
> 'o' - Octal format
> 'x' - Hex format, lower case
> 'X' - Hex format, upper case
> 'n' - Number format
> '%' - Percentage format
### functools.reduce
```python3=
reduce(function, iterable [, initial]) -> value
```
e.g.
### functools.partial
```python3=
partial(func, *args, **keywords)
"""
return a new function with partial application
of the given arguments and keywords.
"""
```
e.g
```python3=00000000000
indpnt=partial(print,'[\t',']')
indpnt("Hello world!")
```
```python
>>> [ ] Hello world!
```
### filter
```python3=
"""
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""
filter(function or None, iterable) --> filter object
```
### permutaion
```python=
from itertools import *
permutations(iterable, r=None)
# |
# | Return successive r-length permutations of elements in the iterable.
# |
# | permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
combinationss(iterable, r)
```
### sys input
```python=
import sys
for myInput in sys.stdin:
print(myInput)
```
## OpenCV
## numpy
```python=
img2 = add(multiply(img,a),b)
img2 = img*a + b
img3 = (exp(img2.astype(float64)) )
img4 = log(img2)
img2 = clip(img2,0,255).astype(uint8)
img3 = clip(img3,0,255).astype(uint8)
img4 = clip(img4,0,255).astype(uint8)
# A = full(img.shape,a)
# B = full(img.shape,b)
# img22 = (A* img + B)
#img22 = clip(img22,0,255).astype(uint8)
```
* array
```
np.arange(n)
```
* operate
```
A.dot(B) # matrix mul
A.any() # if 1 in A return 1
A.all() # all 1 return 1
A.sum(axis=0)
#axis = 要加總的(0,1,2,3,4) if 0 --> (1,2,3,4) 3--> (0,1,2,4)
A > 10 # -->[T,F.....] 看該項>10?
```
## pandas
### str
#### 🔧 基本處理
| 方法 / 屬性 | 說明 | 範例 |
|--------------------|--------------------------------|------------------------------|
| `str.upper()` | 全部轉大寫 | `'foo' → 'FOO'` |
| `str.lower()` | 全部轉小寫 | `'FOO' → 'foo'` |
| `str.title()` | 每個單字首字母大寫 | `'foo bar' → 'Foo Bar'` |
| `str.capitalize()` | 首字大寫,其餘小寫 | `'foo BAR' → 'Foo bar'` |
| `str.strip()` | 移除前後空白 | `' hi ' → 'hi'` |
| `str.lstrip()` | 移除左側空白 | `' hi' → 'hi'` |
| `str.rstrip()` | 移除右側空白 | `'hi ' → 'hi'` |
| `str.zfill(w)` | 用 0 補足寬度 w | `'5'.zfill(3) → '005'` |
| `str.pad(w)` | 置左/右/中補齊寬度 | `'a'.pad(3) → ' a'` |
| `str.center(w)` | 中間對齊 | `'a'.center(3) → ' a '` |
---
#### 🔍 搜尋與比對
| 方法 / 屬性 | 說明 | 範例 |
|----------------------|-------------------------------|--------------------------------|
| `str.contains(p)` | 是否包含字串 / regex | `'abc'.contains('b') → True` |
| `str.startswith(p)` | 是否以某字串開頭 | `'abc'.startswith('a') → True`|
| `str.endswith(p)` | 是否以某字串結尾 | `'abc'.endswith('c') → True` |
| `str.match(p)` | 是否整體符合 regex | `'123'.match(r'\d+')` |
| `str.find(sub)` | 傳回子字串位置,找不到 -1 | `'abc'.find('b') → 1` |
| `str.rfind(sub)` | 從右邊找字串位置 | `'abcabc'.rfind('b') → 4` |
---
#### ✂️ 分割、取代與擷取
| 方法 / 屬性 | 說明 | 範例 |
|------------------------|-------------------------------------|-----------------------------------|
| `str.replace(a, b)` | 替換文字(支援 regex) | `'abc'.replace('b','x') → 'axc'` |
| `str.split(sep)` | 用分隔符拆成 list | `'a@b'.split('@') → ['a','b']` |
| `str.rsplit(sep)` | 從右邊分割 | `'a@b@c'.rsplit('@', 1)` |
| `str.extract(r'()')` | 擷取符合 regex 的 group(只抓括號) | `'a@b.com' → 'b.com'` |
| `str.extractall(r'()')`| 抓出所有符合的 capture group | 適合多重擷取 |
| `str.get(i)` | 從 list/tuple 中取第 i 個元素 | `['a','b'].get(0) → 'a'` |
| `str.join('-')` | 把 list 用符號串起來 | `['a','b'] → 'a-b'` |
---
#### 🧪 類型判斷(布林)
| 方法 / 屬性 | 說明 | 範例 |
|---------------------|----------------------------|-------------------------|
| `str.isalpha()` | 是否全為英文字母 | `'abc' → True` |
| `str.isdigit()` | 是否全為數字 | `'123' → True` |
| `str.isalnum()` | 是否為英數混合 | `'a1' → True` |
| `str.isspace()` | 是否全部為空白 | `' ' → True` |
| `str.isnumeric()` | 是否為數字(含 ½, ⅓ 等) | `'⅓' → True` |
| `str.isdecimal()` | 是否為十進制數字 | `'2' → True` |
---
#### 🧩 其他實用功能
| 方法 / 屬性 | 說明 | 範例 |
|---------------------|-------------------------------|----------------------------|
| `str.len()` | 字串長度 | `'abc'.len() → 3` |
| `str.slice(1,3)` | 切出子字串 | `'hello' → 'el'` |
| `str.cat()` | 合併多個 Series | 可指定分隔符 |
| `str.repeat(n)` | 重複 n 次 | `'ab'.repeat(3) → 'ababab'`|
| `str.encode()` | 字串轉 bytes | `'hi'.encode('utf-8')` |
| `str.normalize()` | unicode 正規化(需額外套件) | `'é'.normalize() == 'é'` |
---
> ✅ 註:所有方法皆自動向量化,會作用在整個 Series 上。