iT邦幫忙

2025 iThome 鐵人賽

DAY 21
0
Software Development

學會 Python 不可怕:我每天學一點的 30 天筆記系列 第 21

Day21 : 字串處理技巧 – f-string、格式化、常用方法

  • 分享至 

  • xImage
  •  
  • f-string:最方便的字串插值方式
  • 傳統格式化:format()、% 語法
  • 常用字串方法(處理大小寫、搜尋、替換、分割...)

1. f-string:最現代、最推薦的寫法
https://ithelp.ithome.com.tw/upload/images/20251005/20178872HDakSFdhA5.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251005/20178872D9xCUD3GhF.png
在字串前面加上 f,裡面用 {} 插入變數或運算式,Python 會自動幫你把變數轉成字串格式
f-string 甚至可以直接放「運算式」:
https://ithelp.ithome.com.tw/upload/images/20251005/20178872aOh6wO49Ly.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251005/20178872EpelIh3q1p.png

2. 傳統的字串格式化方法
(1) .format() 寫法:
https://ithelp.ithome.com.tw/upload/images/20251005/20178872RmumqXwbeP.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251005/201788725Pzr7LCAzZ.png

  • 字串裡的 {} 是「預留空位」,.format(name, age) 會依照順序,把變數值放進去
  • 用.format() 方法來做字串格式化,功能跟 f-string 類似,但語法稍微舊一點

(2) % 語法(舊式但常見):
https://ithelp.ithome.com.tw/upload/images/20251005/201788722Pry2Aahtp.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251005/20178872NghZK78y9x.png
%s:插入字串
%d:插入整數
%f:插入浮點數

3. 常用字串方法

  • .upper() : 全部轉大寫 ex : "python".upper() → "PYTHON"
  • .lower() : 全部轉小寫 ex : "HELLO".lower() → "hello"
  • .title() : 每個字首大寫 ex : "hello world".title() → "Hello World"
  • .strip() : 去除前後空白 ex : " hi ".strip() → "hi"
  • .replace(a, b) : 取代字串 ex : "apple".replace("a", "A") → "Apple"
  • .split() : 切割成列表 ex : "a,b,c".split(",") → ['a', 'b', 'c']
  • .join(list) : 合併列表成字串 ex : ",".join(["a", "b", "c"]) → "a,b,c"

4. 練習 1 : 自我介紹
https://ithelp.ithome.com.tw/upload/images/20251005/201788725QUB3IwFgn.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251005/20178872RfYjHKunWO.png

  • input() 讀進來的資料預設都是字串 (string)。所以即使輸入數字「21」,它的型態也是 "21"(文字),而不是整數
  • 前面的 f 代表這是一個格式化字串
  • f"..." : f-string,能在字串中插入變數
  • {name} 會被替換成使用者輸入的名字,{age} 會被替換成年齡

5. 練習 2 : 資料清理
https://ithelp.ithome.com.tw/upload/images/20251005/20178872jNDWlAYQBh.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251005/20178872gbuF95fqJ4.png

  • 變數 text,內容裡的字串前後都有兩個空白(這是刻意留的)
  • strip() 的功能是:去掉字串開頭和結尾的空白字元(包含空格、換行符號)
  • replace(舊字, 新字):把字串裡原有的內容換成新的內容

上一篇
Day20 : 檔案讀寫 – 讀取文字檔、寫入檔案
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言