split() 可以依照指定的分隔符號,把字串拆成一個串列 (list)
text = "apple,banana,cherry"
fruits = text.split(",") # 用逗號分割
print(fruits)
輸出:
['apple', 'banana', 'cherry']
replace() 可以把字串中特定的文字換掉
sentence = "I like apple"
new_sentence = sentence.replace("apple", "cherry")
print(new_sentence)
輸出:
I like cherry
在 f-string 出現前,常用 format() 來替換字串中的佔位符 {}
name = "Chloe"
age = 20
sentence = "My name is {} and I am {} years old".format(name, age)
print(sentence)
輸出:
My name is Chloe and I am 20 years old
也可以指定位置或名稱:
sentence = "My name is {0}, I am {1}, hello {0}".format("Chloe", 20)
print(sentence)
輸出:
My name is Chloe, I am 20, hello Chloe
f-string 是更直覺的寫法,把變數直接放在字串裡,大括號 {} 會自動替換
name = "Chloe"
age = 20
print(f"My name is {name} and I am {age} years old")
輸出:
My name is Chloe and I am 20 years old
也能做運算或格式控制:
pi = 3.14159
print(f"圓周率約為 {pi:.2f}") # 小數點兩位
輸出:
圓周率約為 3.14
今天學到的字串處理方法讓文字處理變得更靈活!split() 讓我能把長字串拆開處理、replace() 則能快速修正內容!這些技巧在未來做文字分析、資料清理、甚至自動化輸出報告時都會很常用!
明天我要挑戰字串搜尋與迴圈練習,學會如何統計文章中某個字出現幾次,或找出特定字串的位置,並透過迴圈進一步操作文字!