今日對話:字串怎麼處理與格式化?
我的 Prompt(提示詞):
「我已經知道字串是用引號包起來的文字。請教我如何在 Python 中靈活處理字串?例如:怎麼截取字串的一部分?有哪些常用的字串處理方法?以及有沒有比一直用加號拼接更優雅的方式把變數組合進文字裡?」
AI 幫我整理了三大字串處理的精華招式:
關鍵原則:含頭不含尾! 例如 [0:3] 只會拿第 0、1、2 個字元。
可以用負數代表從後面倒數,例如 [-1] 代表最後一個字元。
(1).strip():自動去除字串頭尾無用的空格。
(2).upper() / .lower():全部轉大寫 / 小寫。
(3).replace("舊文字", "新文字"):快速替換字串內容。
看完了AI解說的觀念,我在 VS Code 建立了 day04.py 檔案來練習這些語法:
python
字串切片測試
text = "Python30Days"
print("前 6 個字元:", text[0:6]) # 輸出: Python
print("最後 4 個字元:", text[-4:]) # 輸出: Days
字串內建方法測試
user_input = " alice_wonderland "
clean_input = user_input.strip()
print("清理後的帳號:", clean_input)
print("轉為大寫顯示:", clean_input.upper())
print("替換文字:", clean_input.replace("wonderland", "python"))
f-string 實務寫法
name = "Alex"
days = 4
score = 95.5
使用 f-string 輕鬆將各種型別組合在一起
message = f"嗨 {name}!恭喜你完成 Python 鐵人賽第 {days:02d} 天,獲得 {score} 分!"
print(message)
今天學會了更進階的字串處理與強大的 f-string,覺得f-string語法非常實用。