---
title: Python 陳述式、字串處理
image: https://i.imgur.com/hfBqYPs.jpg
tags: cpsd
---
## 條件句
什麼是條件句
```python
如果 現在就放棄
暑假就開始了
否則
會很累
如果 不上課
如果 不去考試
就會被當
```
條件句 in Python
```python
if 3*7 == 21:
print('不管三七二十一')
```
:::warning
### 注意
冒號跟縮排很重要
:::
## Code Indentation
- 通常翻譯為「縮排」
- 簡單來說就是在排版時往右縮進去的東西
- 就是 Code 前面有幾個空白
- Python 原則上用 4 個空白
- 代表這些內容都在同一個區塊,並有一個開頭
- 例如上面的「就是 Code 前面有幾個空白」就跟現在這句話是同一個區塊
- 然後都是「通常翻譯為『縮排』」的子項目
- 當然,Indentation 可以有很多層
- 像是這樣就多了一層
- 然後又多了一層
- 也可以跑回來
- 不能有區塊是空的
- 可以用 pass 解決
```python
if 1+2 == 3:
# for fun
# IndentationError:expected an indented block
if 1+2 == 3:
pass
```
:::info
Python 是少數程式語言中縮排具有意義的語言
:::
## if-else
- else: 否則,當條件不成立就會執行
- else 要跟 if 在同一層
### if-elif-else
```python
if cmd == 'a':
...
pass
elif cmd == 'b':
...
pass
else:
...
pass
```
- elif 可以理解成 else if
- 只會走進第一個對的
- 全部都不符合才會進 else
:::info
### 重點整理
- 一定會是 if 開頭,除了 if 以外都是非必要的
- 前面條件不符合時繼續判斷某些條件,用 elif
- 前面全部都錯了的時候做某些事情,用 else
- 可以有很多個 elif,但 if、else 只會有一個
:::
## 判斷式
如果判斷是不是布林值(True or False),會被強制轉換
- None
- 0, 0.0, 0+0j, 0j
- '', ""
- ( ), [ ], { }
以上會被轉成 False 其餘都是 True
:::info
### De Morgan's laws
笛摩根定理、對偶律
[-> wiki <-](https://zh.wikipedia.org/zh-tw/%E5%BE%B7%E6%91%A9%E6%A0%B9%E5%AE%9A%E5%BE%8B)
「A 且 B」的相反是「非 A 或 非 B」
「A 或 B」的相反是「非 A 且 非 B」
判斷是很複雜時很好用
:::
```python
False and True or True
```
是 True 還是 False
```python
(False and True) or True # True
False and (True or True) # False
```
[注意運算子的次序](https://docs.python.org/zh-tw/3/reference/expressions.html#operator-precedenc)
善用括號,可以大幅增加可讀性
有時候運算子可以接在一起
```python
1 < 2 < 3 <= 3 # True
# (1 < 2) and (2 < 3) and (3 <= 3)
```
方便的寫法但有時候會出問題
```python
a = 1
b = 2
a is None == b is None
# 直覺:
# (a is None) == (b is None)
# False == False
# True
# 實際上:
# (a is None) and (None == b) and (b is None)
# False and False and False
# False
```
所以善用括號
## Loop
### while
不知道要跑幾次
有明確結束條件(沒有也是可以)
```python
while 判斷條件:
要重複做的事
記得要縮排和加冒號
區塊一樣不能空白
```
### for
明確知道要跑幾次
有可迭代
```python
for 變數 in 可迭代器 :
要做的事
```
:::warning
禁忌:在 for 裡面修改可迭代器
:::
### Iterable 可迭代
- 可以一次回傳自己內一個元素的物件
- 可以分成一項一項的東西
- 例:
- list [1,2,3]
- tuple (1,2,3)
- Dictionary {‘a’:1,’b’:2,’c’:3}
- Set {1,2,3}
- String ”abcd”
[視覺化程式碼](https://pythontutor.com/visualize.html#mode=edit)
### range()
`range(start[, stop[, step]])`
生成一個型態為 range 類似 list 的迭代器
三個參數都可為負值
## String
基本特性
- 長度
```python
len('abcd') # 4
```
- 索引 indexing
```python
'abcd'[0] # a
```
- 迭代 iterable
```python
for x in 'abcd':
print(x, end=' ')
# a b c d
```
- 切片 slicing
```python
s = 'abcd'
s[1:3] # bc
```
> 切片語法
> `string[start:end:step]`
> 索引跟step也可以是負數
>
> | a | b | c | d | |
> |:--:|:--:|:--:|:--:|:-:|
> | 0 | 1 | 2 | 3 |4|
> | -4 | -3 | -2 | -1 |
>
> :::info
> Python 中大多數的範圍都是左閉右開的區間
> 即包含開頭但不包含結尾
> :::
- 不可變的 Immutable
字串中的值不能被改變
但可以透過其他方式(e.g., replace())達成類似的效果
```python
s = 'abcd'
s[0] = 'z'
# TypeError: 'str' object does not support item assignment
# s = s.replace('a', 'z')
```
- 字串運算
`+`可用於連接字串
`*`可視為`+`的展開,用來重複字串
```python
'a'+'b' # 'ab'
'a'*5 # 'aaaaa'
```
- 字串比較
基於字典序的比較
```python
'a' < 'b' # True
```
### 字串處理
#### `replace(old, new[, count])`
> Return a copy with all occurrences of substring old replaced by new.
```python
s = 'Hello, world!'
s.replace('world', 'cpsd') # 'Hello, cpsd!'
```
#### `find(sub, [start[, end]])`
> Return the lowest index in S where substring sub is found, such that sub is contained within S\[start:end\].
回傳第一個找到的索引值,未找到回傳-1
```python
s = 'Hello, cpsd, cpsd, cpsd, and, cpsd'
s.find('cpsd') # 7
```
:::info
`find()` v.s. `in`
find() 跟 in 都能檢查字串中是否包含查詢的子字串,只有在需要知道子字串位置時才應使用 find()
```python
s = 'Hello, cpsd'
s.find('cpsd') # 7
'cpsd' in s # True
```
:::
#### `split(sep[, maxsplit])`
> Return a list of the words in the string, using sep as the delimiter string.
```python
s = 'Hello, cpsd'
s.split(',') # ['Hello', 'cpsd']
s.split() # ['Hello,', ' cpsd']
```
#### `join(iterable)`
> Concatenate any number of strings.
```python
a = ['Hello', ', ', 'cpsd']
''.join(a) # 'Hello, cpsd'
```
#### `strip([chars])`
> Return a copy of the string with leading and trailing whitespace removed.
> If chars is given and not None, remove characters in chars instead.
```python
s = 'Hello, cpsd'
s.strip('deloH') # ', cps'
```
#### 其他好用的東西~~自己看~~
- `isalpha()`, `isdight()`, `islower()`, `isupper()`
- `lower()`, `upper()`
- `lstrip()`, `rstrip()`
- `ljust()`, `rjust()`
- `zfill()`
### format string 格式化字串
把一組年、月、日、時、分、秒串成一個字串
```python
year = '2022'
month = '03'
day = '09'
hour = '13'
mi = '20'
sec = 55.123456789
```
```python
print(year+'/'+month+'/'+day+' '+hour+':'+mi+':'+str(sec))
# 2022/03/09 13:20:55.123456789
```
#### `format()`
> Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
```python
print('{}/{}/{} {}:{}:{}'.format(year, month, day, hour, mi, sec))
# 2022/03/09 13:20:55.123456789
```
小數點有點多?
```python
print('{}/{}/{} {}:{}:{:.2f}'.format(year, month, day, hour, mi, sec))
# 2022/03/09 13:20:55.12
```
perfect
### f-string
```python
print(f'{year}/{month}/{day} {hour}:{mi}:{sec:.2f}')
# 2022/03/09 13:20:55.12
```