Python 字串 (str) 型別詳解:操作、方法、格式化與應用
在 Python 程式設計中,字串 (str) 是一種用於表示文字資料的序列型別。本文將深入探討 Python 字串的各個方面,包括定義、表示方式、基本操作、常用方法、字串格式化,以及實際應用。
什麼是字串 (str)?
字串是由零個或多個字元組成的序列。在 Python 中,字串屬於 str 型別,並且是不可變的 (immutable),這意味著一旦建立後,就不能修改其內容 (但可以透過操作建立新的字串)。
字串的表示方式
Python 中有多種方式可以表示字串:
- 單引號 ('): 'Hello, world!'
- 雙引號 ("): "Hello, world!"
- 三引號 (''' 或 """): 用於表示多行字串,或字串內需同時包含單引號和雙引號的場景。
# 單引號
s1 = 'Hello, Python!'
# 雙引號
s2 = "Hello, Python!"
# 三引號 (多行字串)
s3 = '''This is a
multi-line string.'''
# 三引號 (包含引號)
s4 = """This string contains 'single quotes' and "double quotes"."""
print(type(s1)) # 輸出: <class 'str'>
使用建議: 單引號和雙引號功能上完全相同,可互換使用,但建議在同一個專案中保持一致的風格。當字串本身需要包含引號時(例如 "I'm a student"),交錯使用引號可以避免使用跳脫字元。三引號則非常適合用於多行文字或撰寫文件字串 (docstrings)。
字串的基本操作
作為序列型別,字串支援豐富的操作:
- 拼接 (+): 將兩個或多個字串連接起來。
- 重複 (*): 將字串重複多次。
- 索引 ([]): 存取字串中的特定字元 (索引從 0 開始)。
- 切片 ([start:end:step]): 提取字串的一部分。
- 計算長度 (len()): 取得字串的長度 (字元數)。
s1 = "Hello"
s2 = "World"
# 拼接
s3 = s1 + " " + s2
print(s3) # 輸出: Hello World
# 重複
s4 = s1 * 3
print(s4) # 輸出: HelloHelloHello
# 索引
print(s1[0]) # 輸出: H (第一個字元)
print(s1[-1]) # 輸出: o (負數索引表示從後面數)
# 切片
print(s1[1:4]) # 輸出: ell (從索引 1 到 4 (不含 4))
print(s1[::2]) # 輸出: Hlo (從頭到尾,每隔 2 個字元取一個)
print(s1[::-1]) # 輸出: olleH (反轉字串)
# 長度
print(len(s1)) # 輸出: 5
字串的常用方法
Python 的字串物件提供了許多內建方法,可以方便地進行各種字串處理:
- .lower(), .upper(): 轉換為小寫/大寫。
- .strip(), .lstrip(), .rstrip(): 去除頭尾的空白 (或指定字元)。
- .startswith(prefix), .endswith(suffix): 檢查是否以指定字串開頭/結尾。
- .find(sub), .index(sub): 尋找子字串 (找不到時,find 返回 -1,index 引發錯誤)。
- .replace(old, new): 替換子字串。
- .split(sep): 以指定分隔符號分割字串,返回一個串列。
- .join(iterable): 將一個可迭代物件 (例如串列) 中的字串用當前字串當作分隔符連接起來。
- .count(sub): 計算指定子字串出現的次數。
text = " Hello, World! "
print(text.lower()) # 輸出: hello, world!
print(text.upper()) # 輸出: HELLO, WORLD!
print(text.strip()) # 輸出: Hello, World!
print(text.startswith(" H"))# 輸出: True
print(text.find("World")) # 輸出: 10
print(text.replace("Hello", "Hi")) # 輸出: Hi, World!
print(text.strip().split(","))# 輸出: ['Hello', ' World!']
print(text.count('l')) # 輸出: 3
words = ['This', 'is', 'a', 'sentence']
print(' '.join(words)) # 輸出: This is a sentence
字串格式化
將變數的值插入到字串中的過程,稱為字串格式化。Python 提供了多種字串格式化方法,其中 f-string 是最被推薦的方式。
最現代、最簡潔的方式,在字串前加上 f 或 F,並在字串中使用大括號 {} 插入變數或表達式。
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)
使用 {} 作為佔位符,並在 .format() 方法中傳入對應的值。
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
使用 %s (字串)、%d (整數)、%f (浮點數) 等格式化符號,並在 % 後面傳入對應的值 (類似 C 語言的 printf)。
name = "Alice"
age = 30
message = "My name is %s and I am %d years old." % (name, age)
print(message)
字串的應用
字串是程式設計中應用最廣泛的資料型別之一:
- 文字處理: 文件分析、自然語言處理 (NLP)、網頁爬蟲資料提取等。
- 資料輸入/輸出: 格式化輸出、解析使用者輸入或檔案內容。
- 使用者介面: 在應用程式中顯示訊息、提示、錯誤等。
- 網路程式設計: 傳輸和處理 HTTP 請求、API 回應等文字資料。