字串的操作
## Python 字串是內建類別
在 Python 中,字串的型別是 `str`,而 `str` 是 Python 內建的類別。只要使用引號建立文字資料,就會得到一個 `str` 物件:
```python
name = "Alice"
message = 'Hello, Python!'
print(type(name)) # <class 'str'>
print(isinstance(name, str)) # True
```
因為字串是物件,所以可以使用 `str` 類別提供的方法,例如:
```python
name.upper()
```
此外,Python 字串具有以下特性:
- 可以使用單引號、雙引號或三引號建立。
- 可以使用索引與切片取得部分字串。
- 字串是**不可變(immutable)**的,方法通常會回傳新的字串,不會直接修改原字串。
```python
text = "hello"
new_text = text.upper()
print(text) # hello
print(new_text) # HELLO
```
## 常見的字串方法
| 方法 | 功能 | 範例 |
|---|---|---|
| `upper()` | 轉成大寫 | `"hello".upper()` → `"HELLO"` |
| `lower()` | 轉成小寫 | `"HELLO".lower()` → `"hello"` |
| `capitalize()` | 第一個字元大寫 | `"python".capitalize()` → `"Python"` |
| `strip()` | 移除前後空白 | `" hi ".strip()` → `"hi"` |
| `replace(old, new)` | 取代文字 | `"cat".replace("cat", "dog")` |
| `split(separator)` | 分割字串,回傳串列 | `"a,b,c".split(",")` → `["a", "b", "c"]` |
| `join(iterable)` | 將多個字串連接起來 | `"-".join(["2025", "01", "01"])` |
| `find(sub)` | 尋找子字串位置 | `"Python".find("th")` → `2` |
| `startswith(prefix)` | 判斷是否以指定文字開頭 | `"https://".startswith("http")` |
| `endswith(suffix)` | 判斷是否以指定文字結尾 | `"photo.jpg".endswith(".jpg")` |
| `isdigit()` | 判斷是否全部為數字 | `"123".isdigit()` → `True` |
| `isalpha()` | 判斷是否全部為英文字母 | `"Python".isalpha()` → `True` |
## 實務範例一:清理使用者輸入的姓名
使用者輸入的資料可能包含前後空白,甚至大小寫不一致,可以先清理再顯示:
```python
name = input("請輸入姓名:")
clean_name = name.strip().title()
print(f"您好,{clean_name}!")
```
例如輸入:
```text
alice chen
```
輸出:
```text
您好,Alice Chen!
```
這裡使用:
- `strip()`:移除前後空白
- `title()`:將每個單字的第一個字元轉成大寫
## 實務範例二:解析逗號分隔的資料
假設系統收到一段以逗號分隔的商品資料,可以使用 `split()` 拆解,再利用 `strip()` 清除多餘空白:
```python
data = "蘋果, 香蕉, 橘子, 葡萄"
items = [item.strip() for item in data.split(",")]
print(items)
```
輸出:
```python
['蘋果', '香蕉', '橘子', '葡萄']
```
若要再將清單重新組合成一段文字,可以使用 `join()`:
```python
result = "、".join(items)
print(result)
```
輸出:
```text
蘋果、香蕉、橘子、葡萄
```
這個範例常見於處理表單資料、CSV 欄位或使用者輸入內容。
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫