字串操作#
Python 的字串(str)是不可變的字元序列,支援單引號、雙引號或三引號建立。
透過索引、切片與豐富的內建方法,字串處理在 Python 中十分便捷。
建立字串#
字串可以用單引號 ' 或雙引號 " 包住,兩者效果相同:
1
2
3
4
5
6
7
8
9
10
11
12
| s1 = "Hello, World!"
s2 = 'Python 很好學'
# 字串內含引號時,用另一種引號包住
s3 = "It's a good day"
s4 = '他說:"你好"'
# 三引號可以跨行
s5 = """第一行
第二行
第三行"""
print(s5)
|
字串基本操作#
串接與重複#
1
2
3
4
5
6
7
8
9
10
| first = "Hello"
last = "World"
# 串接
greeting = first + ", " + last + "!"
print(greeting) # Hello, World!
# 重複
line = "-" * 20
print(line) # --------------------
|
取得長度:len()#
1
2
| s = "Python"
print(len(s)) # 6
|
索引與切片#
Python 字串可以用索引取得單一字元,索引從 0 開始,也支援負數索引(從尾端算起):
1
2
3
4
5
6
7
8
| s = "Python"
# 012345
# -6-5-4-3-2-1
print(s[0]) # P(第 1 個字元)
print(s[5]) # n(第 6 個字元)
print(s[-1]) # n(最後一個字元)
print(s[-2]) # o(倒數第 2 個字元)
|
切片 (slicing)可以取出一段子字串,語法為 s[start:end:step]:
1
2
3
4
5
6
7
| s = "Python"
print(s[0:3]) # Pyt(取索引 0、1、2)
print(s[2:]) # thon(從索引 2 到結尾)
print(s[:4]) # Pyth(從開頭到索引 3)
print(s[::2]) # Pto(每隔 2 個取一個)
print(s[::-1]) # nohtyP(反轉字串)
|
f-string(格式化字串)#
Python 3.6 以上推薦使用 f-string ,在字串前加 f,用 {} 嵌入變數或運算式:
1
2
3
4
5
6
7
8
9
10
11
12
| name = "Alice"
age = 25
score = 92.5
print(f"你好,{name}!你今年 {age} 歲。")
# 你好,Alice!你今年 25 歲。
print(f"平均分數:{score:.1f}")
# 平均分數:92.5
print(f"2 的 10 次方 = {2 ** 10}")
# 2 的 10 次方 = 1024
|
數字格式化#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| price = 1234567.89
print(f"{price:,}") # 1,234,567.89(千分位逗號)
print(f"{price:.2f}") # 1234567.89(小數 2 位)
print(f"{price:,.0f}") # 1,234,568(千分位,無小數)
ratio = 0.1234
print(f"{ratio:.1%}") # 12.3%(百分比)
num = 42
print(f"{num:05d}") # 00042(補零到 5 位)
print(f"{num:>10}") # 靠右對齊,寬度 10
print(f"{num:<10}") # 靠左對齊
print(f"{num:^10}") # 置中對齊
|
常用字串方法#
大小寫轉換#
1
2
3
4
5
6
| s = "Hello, World!"
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
print(s.title()) # Hello, World!(每個單字首字大寫)
print(s.swapcase()) # hELLO, wORLD!(大小寫互換)
|
去除空白#
1
2
3
4
5
6
7
8
9
| s = " Hello, World! "
print(s.strip()) # "Hello, World!"(去除兩側空白)
print(s.lstrip()) # "Hello, World! "(去除左側)
print(s.rstrip()) # " Hello, World!"(去除右側)
# 也可以指定要去除的字元
s2 = "###Python###"
print(s2.strip("#")) # Python
|
尋找與取代#
1
2
3
4
5
6
7
| s = "I love Python, Python is great"
print(s.find("Python")) # 7(第一次出現的索引)
print(s.find("Java")) # -1(找不到回傳 -1)
print(s.count("Python")) # 2(出現次數)
print(s.replace("Python", "Go")) # I love Go, Go is great
print(s.replace("Python", "Go", 1)) # I love Go, Python is great(只取代第 1 次)
|
分割與合併#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # split():分割字串,回傳 list
csv = "Alice,Bob,Charlie"
names = csv.split(",")
print(names) # ['Alice', 'Bob', 'Charlie']
sentence = "I love Python"
words = sentence.split() # 以空白分割(自動處理多個空格)
print(words) # ['I', 'love', 'Python']
# join():合併串列成字串
result = " - ".join(names)
print(result) # Alice - Bob - Charlie
path_parts = ["home", "user", "documents"]
path = "/".join(path_parts)
print(path) # home/user/documents
|
判斷開頭與結尾#
1
2
3
4
5
| filename = "report_2026.pdf"
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True
print(filename.endswith(".xlsx")) # False
|
判斷字串內容#
1
2
3
4
5
6
| print("123".isdigit()) # True(全部是數字)
print("abc".isalpha()) # True(全部是字母)
print("abc123".isalnum()) # True(字母或數字)
print(" ".isspace()) # True(全部是空白)
print("Hello".isupper()) # False
print("HELLO".isupper()) # True
|
字串是不可變的#
字串建立後 不能修改 ,每次操作都會產生新的字串:
1
2
3
4
5
6
| s = "Hello"
# s[0] = "h" # ❌ 錯誤!字串不支援索引賦值
# 正確做法:建立新字串
s = s.lower()
print(s) # hello
|
常用範例#
判斷是否為回文#
1
2
3
| word = "racecar"
is_palindrome = word == word[::-1]
print(is_palindrome) # True
|
計算每個字元出現次數#
1
2
3
4
| text = "hello world"
for char in set(text):
if char != " ":
print(f"'{char}' 出現 {text.count(char)} 次")
|
多行文字處理#
1
2
3
4
5
| data = "Alice,25,Taipei\nBob,30,Kaohsiung\nCharlie,22,Taichung"
for line in data.strip().split("\n"):
name, age, city = line.split(",")
print(f"{name} 住在 {city},{age} 歲")
|