Python 進階 16:字串進階操作

🎯 學習目標

1. 學會常用字串方法
2. 學會切割、合併字串
3. 學會大小寫轉換
4. 能使用 f-string 格式化字串

📘 知識說明

字串可以做很多操作:

常用方法:
- len() → 計算長度
- upper() / lower() → 大小寫轉換
- split() → 分割字串
- join() → 合併字串

f-string 可以用來格式化字串:
name = "Amy"
print(f"Hello {name}")

💻 範例程式
text = "Python is fun"

print(len(text))
print(text.upper())
print(text.lower())

words = text.split()
print(words)

joined = "-".join(words)
print(joined)

name = "Amy"
print(f"Hello {name}")
📝 練習任務 ▼

1. 將 "hello world" 改成大寫
2. 用 split() 分割字串
3. 用 join() 合併成 "hello-world"
4. 嘗試用 f-string 印出 "Hi, Amy!"

📌 小結 ▼

✔ 字串有很多方法
✔ f-string 可以插入變數
✔ split() 與 join() 方便處理多段文字

程式編輯器
程式輸出