Python 的字串(str)是有序的字元序列,用單引號或雙引號建立,支援索引取出單一字元、切片取得子字串,以及豐富的內建方法。本文涵蓋字串的建立語法、正向與反向索引、切片的 start/stop/step 三參數用法,以及 .upper()、.lower()、.split()、len() 等常用操作,建立穩固的字串操作基礎。
本文目錄
什麼是 Python 字串?
字串就像一串珠子,每顆珠子是一個字元,每個位置都有固定編號(索引),從左邊的 0 開始,也可以從右邊的 -1 反向存取。Python 字串是「不可變(immutable)」序列,意思是你無法直接修改某個字元,只能透過切片和拼接建立新字串。字串可以用單引號 '...' 或雙引號 "..." 建立,若字串本身包含其中一種引號,就用另一種包覆即可。
核心語法
# ── 範例 1:建立字串 ──
s1 = 'Hello' # 單引號
s2 = "World" # 雙引號
s3 = "I'm Python" # 字串內含單引號,用雙引號包覆
s4 = 'She said "Hi"' # 字串內含雙引號,用單引號包覆
s5 = "Hello\nWorld" # \n 是換行符,\t 是定位符
# 多行字串(三引號)
s6 = """第一行
第二行
第三行"""
print(len(s1)) # 5(len() 計算字元總數,含空白)
print(type(s1)) #
# ── 範例 2:索引(取單一字元)──
word = "Python"
# P y t h o n
# 正向: 0 1 2 3 4 5
# 反向: -6 -5 -4 -3 -2 -1
print(word[0]) # P(第一個字元)
print(word[3]) # h
print(word[-1]) # n(最後一個字元)
print(word[-2]) # o(倒數第二個字元)
# ── 範例 3:切片(取子字串)── 語法:[start:stop:step]
s = "ABCDEFGHIJK"
print(s[2:]) # 從 index 2 到結尾 → CDEFGHIJK
print(s[:4]) # 從開頭到 index 4(不含)→ ABCD
print(s[2:7]) # index 2 到 7(不含)→ CDEFG
print(s[::2]) # 從頭到尾,步長 2 → ACEGIK
print(s[1:8:2]) # index 1 到 8,步長 2 → BDFH
print(s[::-1]) # 步長 -1 → 反轉字串 KJIHGFEDCBA
切片的
stop是「到此為止但不包含」。例如s[2:7]取的是 index 2、3、4、5、6,不包含 index 7。這個「左閉右開」原則貫穿 Python 的所有序列操作,記住它能避免大量 off-by-one 的錯誤。
規則與注意事項
| 規則 | ✅ 正確範例 | ❌ 錯誤範例 / 陷阱 |
|---|---|---|
| 字串是不可變的,不能直接改字元 | new = "P" + s[1:] |
s[0] = "P"(TypeError!) |
索引從 0 開始,最後一個是 len-1 |
s[0] 取第一個字元 |
s[len(s)](IndexError!) |
| 切片超出範圍不會報錯 | s[0:100] 直接回傳完整字串 |
誤以為會 IndexError |
| 空白與換行符也算字元數 | len("Hi!") == 3 |
誤以為空白不計入 len() |
| 字串 + 字串才能串接,不能加數字 | "No." + str(5) |
"No." + 5(TypeError!) |
常見錯誤與防呆
錯誤一:嘗試直接修改字串字元
# ❌ 錯誤寫法(TypeError: 'str' object does not support item assignment)
name = "Sam"
name[0] = "P" # TypeError!
# ✅ 正確寫法:切片+串接建立新字串
name = "Sam"
name = "P" + name[1:]
print(name) # Pam
錯誤二:索引超出範圍
# ❌ 錯誤寫法(IndexError: string index out of range)
s = "Hi"
print(s[5]) # IndexError!
# ✅ 正確寫法:取最後一個字元用 -1
print(s[-1]) # i
# 或先確認長度
if len(s) > 2:
print(s[2])
錯誤三:字串與數字直接串接
# ❌ 錯誤寫法(TypeError: can only concatenate str (not "int") to str)
score = 95
print("你的分數是 " + score) # TypeError!
# ✅ 正確寫法:用 str() 轉型,或直接用 f-string
print("你的分數是 " + str(score)) # 你的分數是 95
print(f"你的分數是 {score}") # 你的分數是 95
進階用法
常用字串方法
s = " Hello, Python World! "
# 大小寫轉換
print(s.upper()) # 全大寫
print(s.lower()) # 全小寫
print(s.title()) # 每個單字首字母大寫
# 去除空白
print(s.strip()) # 去除頭尾空白 → "Hello, Python World!"
print(s.lstrip()) # 只去左側空白
print(s.rstrip()) # 只去右側空白
# 查詢與替換
print(s.count("o")) # 計算 "o" 出現次數 → 3
print(s.find("Python")) # 回傳首次出現的 index → 9(含頭部空白)
print(s.replace("World", "AI")) # 替換 → " Hello, Python AI! "
# 判斷
print("123".isdigit()) # True(全為數字字元)
print("abc".isalpha()) # True(全為英文字母)
print(" ".isspace()) # True(全為空白)
split() 分割與 join() 合併
# split():依分隔符拆成串列
sentence = "apple,banana,cherry"
fruits = sentence.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
data = "2026-03-26"
parts = data.split("-")
print(parts) # ['2026', '03', '26']
# join():將串列合併成字串
words = ["Python", "is", "awesome"]
result = " ".join(words) # 用空格連接
print(result) # Python is awesome
csv_line = ",".join(["100", "200", "300"])
print(csv_line) # 100,200,300
字串乘法與 in 運算子
# 字串乘法:重複輸出
print("-" * 30) # 印出 30 個橫線(常用作分隔線)
print("Ha" * 3) # HaHaHa
# in 運算子:檢查子字串是否存在
text = "量化交易策略開發"
print("量化" in text) # True
print("機器學習" in text) # False
# 實用場景:過濾日誌關鍵字
log = "ERROR: Connection timeout at 14:32"
if "ERROR" in log:
print("發現錯誤訊息,請檢查日誌")
🏮 煉金師小叮嚀
在量化策略開發中,我最常用 切片與 split() 處理 API 回傳的時間字串,例如把 "2026-03-26T14:32:00" 拆成日期與時間兩部分。另外要提醒:字串方法永遠回傳新字串,不修改原本的值,所以別忘了把結果賦值回去,例如 s = s.strip(),不然你會以為方法沒效果,其實是結果被你丟掉了。
Tags
python