Python 字串 (11):不可變性的威力——疊代、成員測試與條件判斷實戰

字串是不可變(immutable)的序列:一旦建立就不能原地改內容。這不是限制,而是優點——讓字串在多處共用更安全、行為更可預期,也能作為字典的鍵使用。本篇延續字串基礎,聚焦三件事:

  1. 何謂不可變性、為何需要「重新建立新字串」;
  2. 如何逐字疊代做計數、轉換與搜尋;
  3. inand / or / not 把文字判斷寫得又短又清楚。

看完你就能把「看起來是文字」的資料,轉成可分析、可判斷的結構化訊息。

Python code snippet showing string immutability error when trying to modify a string

字串的不可變性 (Immutability)

字串是不可變的 (Immutable)

這意味著一旦創建了字串,就無法更改它的內容。

當我們進行字串操作時,實際上是創建了一個全新的字串。

可變性 (Mutability)

  • 可變 (Mutable) 的資料類型可以被修改
  • 不可變 (Immutable) 的資料類型不能被修改
# 這將產生錯誤
name = "Tom"
name[0] = "J" 
# TypeError: 'str' object 
# does not support item assignment

# 正確方法:創建新字串
name = "Tom"
new_name = "J" + name[1:]
print(new_name) # 輸出: "Jom"
Python code showing a for loop iterating through a string

疊代字串 (Iterating through Strings)

因為字串是字符的序列,所以可以使用迴圈 (Loops) 來疊代處理每個字符:

def print_each_letter(word):
    for letter in word:
        print(letter)
        
favorite_color = "blue"
print_each_letter(favorite_color)
# 輸出:
# 'b'
# 'l'
# 'u'
# 'e'
    

疊代的應用

疊代字串為我們提供了強大的字串處理能力,例如:

  • 統計特定字符出現的次數
  • 將字串轉換為其他格式
  • 搜尋特定模式
  • 逐字符處理文本

字串與條件判斷 (一)

定義變數

favorite_fruit = "blueberry"
counter = 0
    

迭代字串

for character in favorite_fruit:
    

條件判斷

    if character == "b":
        counter = counter + 1
    

輸出結果

print(counter)  # 輸出: 2
    

這段代碼計算了字串 “blueberry” 中字母 ‘b’ 出現的次數。結合迭代與條件判斷,我們可以實現各種字串分析功能。

Python code showing string conditions with in operator

字串與條件判斷 (二)

使用 in 運算符

in 是檢查一個字串是否包含在另一個字串中的更簡便方法。

# 檢查單個字符
print("e" in "blueberry")  # 輸出: True
print("a" in "blueberry")  # 輸出: False

# 檢查子字串
print("blue" in "blueberry")  # 輸出: True
print("blue" in "strawberry")  # 輸出: False
    

組合多個布林表達式

使用 andornot 可以組合多個條件:

# 兩個條件都為 True 才返回 True
print("e" in "blueberry" and 
      "e" in "carrot")  
# 輸出: False

# 第一個為 True 且第二個為 False 時返回 True
print("e" in "blueberry" and 
      not "e" in "carrot")  
# 輸出: True
    

總結

思考模式:把字串當「序列」看待(索引、切片、迭代),再用布林邏輯組合規則,就能寫出清楚的文字處理程式。

不可變性s[i] = ... 會報錯;任何「修改」其實都是建立新字串(如 "J" + s[1:])。

迭代字串for ch in s: 能逐字處理;結合計數與條件即可完成常見分析(如統計某字元出現次數)。

成員測試sub in s 判斷字元/子字串是否存在,直覺且高效;可搭配 and / or / not 建立複合條件。

實務小撇步:需要大量串接時,避免在迴圈裡用 + 疊字串,改用 ''.join(parts) 更有效率。

思考模式:把字串當「序列」看待(索引、切片、疊代),再用布林邏輯組合規則,就能寫出清楚的文字處理程式。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

返回頂端