Skip to content

Python 字串指南:基礎操作、格式化

在 Python 程式設計中,字串 (string) 是一種極其重要且常用的數據類型。無論是處理用戶輸入、讀寫檔案、網絡通訊,還是數據分析,字串都扮演著不可或缺的角色。這篇文章將帶你深入了解 Python 字串的各個方面,從基本概念到進階操作和格式化技巧。

📜 什麼是 Python 字串?

在 Python 中,字串是由一連串字符組成的序列。你可以使用單引號 (')、雙引號 (") 或三引號 ('''""") 來創建字串。

python
my_string1 = '你好,世界!'
my_string2 = "Hello, Python!"
my_string3 = """這是一個
跨越多行的
字串。"""
my_string4 = '''這也是一個
跨越多行的
字串。'''

print(my_string1)
print(my_string2)
print(my_string3)
print(my_string4)

一個重要的特性是,Python 中的字串是 不可變的 (immutable)。這意味著一旦字串被創建,它的內容就不能被修改。任何對字串的「修改」操作,實際上都會創建一個新的字串。

✂️ 字串的索引與切片 (Indexing and Slicing)

由於字串是序列,你可以透過索引來存取字串中的個別字符,或透過切片來獲取子字串。

索引 (Indexing)

索引從 0 開始,也可以使用負數索引從字串末尾開始存取。

python
text = "Python"
print(text[0])   # 輸出: P (第一個字符)
print(text[2])   # 輸出: t
print(text[-1])  # 輸出: n (最後一個字符)
print(text[-2])  # 輸出: o

切片 (Slicing)

切片允許你獲取字串的一部分。語法是 [start:stop:step]

  • start: 開始索引(包含)。
  • stop: 結束索引(不包含)。
  • step: 步長(可選,預設為 1)。
python
text = "Hello, World!"
print(text[0:5])    # 輸出: Hello (從索引 0 到 4)
print(text[:5])     # 輸出: Hello (從頭開始到索引 4)
print(text[7:])     # 輸出: World! (從索引 7 到結尾)
print(text[::2])    # 輸出: Hlo ol! (每隔一個字符取一個)
print(text[::-1])   # 輸出: !dlroW ,olleH (反轉字串)

🔗 常見的字串操作

Python 提供了豐富的操作來處理字串。

連接 (Concatenation)

使用 + 運算符可以連接兩個字串。

python
str1 = "Hello"
str2 = "Python"
result = str1 + ", " + str2 + "!"
print(result)  # 輸出: Hello, Python!

重複

使用 * 運算符可以重複一個字串。

python
str_repeat = "Ha" * 3
print(str_repeat)  # 輸出: HaHaHa

長度

使用 len() 函數可以獲取字串的長度(字符數量)。

python
text = "Python is fun"
print(len(text))  # 輸出: 13

成員檢查

使用 innot in 關鍵字可以檢查一個子字串是否存在於某個字串中。

python
text = "Welcome to Hong Kong"
print("Hong Kong" in text)  # 輸出: True
print("Tokyo" not in text)  # 輸出: True

🛠️ 常用的字串方法

Python 字串對象有許多內建方法,可以執行各種有用的操作。由於字串是不可變的,這些方法通常會返回一個新的字串,而不是修改原始字串。

大小寫轉換

  • upper(): 將所有字符轉換為大寫。
  • lower(): 將所有字符轉換為小寫。
  • capitalize(): 將字串的第一個字符轉換為大寫,其餘字符轉換為小寫。
  • title(): 將字串中每個單詞的首字母轉換為大寫。
  • swapcase(): 將字串中的大寫字母轉換為小寫,小寫字母轉換為大寫。
python
text = "hello WORLD"
print(text.upper())       # 輸出: HELLO WORLD
print(text.lower())       # 輸出: hello world
print("python programming".capitalize()) # 輸出: Python programming
print("python programming".title())      # 輸出: Python Programming
print("PyThOn".swapcase())    # 輸出: pYtHoN

查找與取代

  • find(substring): 查找子字串,如果找到則返回第一個匹配的起始索引,否則返回 -1。
  • rfind(substring): 從右邊開始查找子字串。
  • index(substring): 類似 find(),但如果找不到子字串會拋出 ValueError 異常。
  • rindex(substring): 類似 rfind(),但如果找不到子字串會拋出 ValueError 異常。
  • replace(old, new): 返回一個新字串,其中所有 old 子字串都被 new 子字串取代。
  • count(substring): 返回子字串在字串中出現的次數。
python
text = "She sells seashells by the seashore."
print(text.find("sea"))        # 輸出: 10
print(text.rfind("sea"))       # 輸出: 27 (seashore)
print(text.index("sells"))     # 輸出: 4
# print(text.index("ocean"))   # 這會引發 ValueError

new_text = text.replace("sells", "buys")
print(new_text)              # 輸出: She buys seashells by the seashore.
print(text.count("sh"))      # 輸出: 2

檢查類方法

這些方法通常返回布爾值 (True/False)。

  • startswith(prefix): 檢查字串是否以指定的前綴 prefix 開頭。
  • endswith(suffix): 檢查字串是否以指定的後綴 suffix 結尾。
  • isalpha(): 如果字串中所有字符都是字母且字串不為空,則返回 True。
  • isdigit(): 如果字串中所有字符都是數字且字串不為空,則返回 True。
  • isalnum(): 如果字串中所有字符都是字母或數字且字串不為空,則返回 True。
  • isspace(): 如果字串中所有字符都是空白字符(如空格、tab、換行符)且字串不為空,則返回 True。
  • islower(): 如果字串中所有字母字符都是小寫且至少包含一個字母字符,則返回 True。
  • isupper(): 如果字串中所有字母字符都是大寫且至少包含一個字母字符,則返回 True。
python
filename = "document.txt"
print(filename.startswith("doc"))  # 輸出: True
print(filename.endswith(".pdf"))   # 輸出: False

print("Python".isalpha())    # 輸出: True
print("12345".isdigit())     # 輸出: True
print("Python3".isalnum())   # 輸出: True
print("   ".isspace())       # 輸出: True
print("python".islower())    # 輸出: True
print("PYTHON".isupper())    # 輸出: True

清理與分割

  • strip(): 移除字串頭尾的空白字符(或指定的字符)。
  • lstrip(): 移除字串頭部的空白字符(或指定的字符)。
  • rstrip(): 移除字串尾部的空白字符(或指定的字符)。
  • split(separator): 以 separator 為分隔符將字串分割成一個列表 (list)。如果未指定 separator,則預設以空白字符分割。
  • join(iterable): 將 iterable (例如列表) 中的所有字串元素連接成一個單一的字串,並以調用該方法的字串作為分隔符。
python
text_with_spaces = "   Hello, Python!   "
print(text_with_spaces.strip())   # 輸出: Hello, Python!
print(text_with_spaces.lstrip())  # 輸出: Hello, Python!
print(text_with_spaces.rstrip())  # 輸出:    Hello, Python!

data = "apple,banana,cherry"
fruits = data.split(',')
print(fruits)  # 輸出: ['apple', 'banana', 'cherry']

words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)  # 輸出: Python is awesome

📝 字串格式化

將變數的值嵌入到字串中是一項常見任務。Python 提供了多種字串格式化方法。

1. 百分號 (%) 格式化 (舊式)

這是早期 Python 版本中主要的格式化方法,類似 C 語言的 printf

python
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)  # 輸出: My name is Alice and I am 30 years old.
  • %s 用於字串
  • %d 用於整數
  • %f 用於浮點數

雖然仍然可用,但這種方法在新代碼中已不推薦,因為可讀性和靈活性較差。

2. str.format() 方法 (新式)

這是 Python 2.6+ 引入的更強大和靈活的方法。

python
name = "Bob"
age = 25
# 通過位置
formatted_string1 = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string1)

# 通過索引
formatted_string2 = "My name is {0} and I am {1} years old. {0} is a good name.".format(name, age)
print(formatted_string2)

# 通過關鍵字參數
formatted_string3 = "My name is {n} and I am {a} years old.".format(n=name, a=age)
print(formatted_string3)

# 格式規範
pi = 3.1415926
formatted_pi = "Pi is approximately {:.2f}".format(pi) # 保留兩位小數
print(formatted_pi) # 輸出: Pi is approximately 3.14

str.format() 提供了更多控制,例如對齊、填充、精度等。

3. f-Strings (格式化字串字面值, Formatted String Literals) (建議使用)

f-Strings 是 Python 3.6+ 引入的,被認為是目前最 Pythonic、最易讀且通常最快的方法。

python
name = "Charlie"
age = 40
score = 95.5

# 基本用法
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 輸出: My name is Charlie and I am 40 years old.

# 可以在 {} 中執行表達式
formatted_string_expr = f"Next year, {name} will be {age + 1} years old."
print(formatted_string_expr) # 輸出: Next year, Charlie will be 41 years old.

# 格式規範
formatted_score = f"{name}'s score is {score:.1f}." # 保留一位小數
print(formatted_score) # 輸出: Charlie's score is 95.5.

# 使用 !r 獲取 repr() 表示, !s 獲取 str() 表示 (預設)
today = "Monday"
print(f"Today is {today!r}.") # 輸出: Today is 'Monday'.

格式化方法比較:

特性%-formattingstr.format()f-Strings
簡潔性中等較冗長非常簡潔
可讀性較差 (尤其多個變數時)良好最好
功能性基本強大,支援複雜格式化強大,支援複雜格式化
效能較慢比 %-formatting 快,比 f-string 慢通常最快
Python 版本所有版本Python 2.6+Python 3.6+
推薦度不推薦用於新代碼可用,但 f-string 更佳強烈推薦

對於新項目,強烈建議使用 f-Strings,因為它們更易讀、更簡潔,並且通常效能更好。

⚙️ 特殊字符與原始字串 (Escape Sequences, Raw Strings)

跳脫序列 (Escape Sequences)

在字串中,反斜線 \ 用作跳脫字符,用於表示一些特殊字符:

  • \n: 換行符
  • \t: Tab 鍵
  • \\: 反斜線本身
  • \': 單引號
  • \": 雙引號
python
print("Line 1\nLine 2")
# 輸出:
# Line 1
# Line 2

print("Path: C:\\Users\\name") # 輸出: Path: C:\Users\name
print('He said, "Hello!"')    # 輸出: He said, "Hello!"
print("She said, 'Hi!'")      # 輸出: She said, 'Hi!'

原始字串 (Raw Strings)

如果你不希望 \ 被解釋為跳脫字符,可以在字串前加上 rR。這在處理正則表達式或 Windows 文件路徑時非常有用。

python
# Windows 路徑,使用原始字串
path = r"C:\Users\new_folder\notes.txt"
print(path)  # 輸出: C:\Users\new_folder\notes.txt

# 正則表達式模式
import re
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
print(pattern) # 輸出: \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b

✨ 總結

Python 中的字串功能強大且靈活。掌握其基本概念、常用操作和格式化技巧,將大大提升你的 Python 程式設計效率。記住字串是不可變的,並且優先考慮使用 f-Strings 進行字串格式化。透過不斷練習,你將能熟練地運用 Python 字串解決各種實際問題。

📚 參考資料

KF Software House