Try   HackMD

Python 資料格式化 / format / f-string / f"{x}"

2024/09/15 整理完成

學習 Python 字串格式化的方式

Python 字串格式化學習資源:

https://myapollo.com.tw/blog/python-f-string-formating-syntax/

https://steam.oxxostudio.tw/category/python/basic/format.html

https://docs.python.org/3/tutorial/introduction.html#text

https://docs.python.org/3/library/string.html#formatstrings

最詳盡舉例+樣板字串+巢狀置換 一些很特別的用法
https://dev.to/codemee/python-de-ge-shi-hua-zi-chuan-gong-neng-4o8

舊版寫法

%(資料型態)格式

flag 前置符號

0 代表 補零
%03d

%(補齊字元)(對齊方式)(占幾位)(資料型態)

  • 靠右 - 靠左
    數字.數字 (最小寬度,最大字元數)

整數部分的最小寬度 (未滿維持)
小數部分的最大精度

資料型態:

常用的

%b 二進位 binary

%d 十進位整數 decimal

%f 浮點數 float

%s 字串

%d 十進制整數

%x 十六進制整數

# python 官方範例 print("%(code_language)s" % {"code_language": "Python"}) # dict 要指定 key 鍵值 # print("有特定的字串" % 資料結構) # print("有特定的字串" % (多個對應參數)) a = '%s world, there are %f dollars!' b = a % ('hello', 2.5) print(b) # hello world, there are 2.500000 dollars! e = 10 f = 2.5 g = "str" print("%d %f %s" % (e, f, g)) h = "%s ,%d ,%d ,%d ,#%02X%02X%02X" print(h % ("alice blue", 240, 240, 250, 240, 240, 250))

BIF 有個 format()

*備註:與.format不同
內建函式,format(參數,"格式化設定")

範例:

num = 123.456 print("結果是", format(num, ".2f")) # 輸出:結果是 123.46

"字串" + "字串" 會自動合併

str.format()

{(位置):(填補字元)(對齊方式)(最小寬度)}.format()

https://docs.python.org/3/library/string.html#grammar-token-format-string-format_spec

color_name = "alice blue" r, g, b = 240, 240, 250 # hex_code = f"#{240:02X}{240:02X}{250:02X}" f-string 用法 # 將 "f0", "f8", "ff" 轉換為整數 r_hex = int("f0", 16) g_hex = int("f8", 16) b_hex = int("ff", 16) Z = "{0:<12} ,{1:3d} ,{2:3d} ,{3:3d} ,#{1:02X}{2:02X}{3:02X}".format(color_name, r, g, b) print(Z) # 加上順序就可以重複使用該參數

f-string

https://docs.python.org/zh-tw/3/library/datetime.html#strftime-and-strptime-behavior

https://quantpass.org/python_datetime/

https://kaochenlong.com/2024/02/29/f-strings-in-python.html

color_name = "alice blue" r, g, b = 240, 240, 250 hex_code = f"#{r:02X}{g:02X}{b:02X}" line = f"{color_name} ,{r} ,{g} ,{b} ,{hex_code}" print(line) # strftime() 與 strptime() # strftime() : string from time,就是將時間資料格式轉換成字串。 # strptime(): string parse time 將字串資料轉換成時間資料格式。 # %Y:%m:%d 年月日 # %B 月份全名 %A 星期全名 # %H:%M:%S 01:19:18 時分秒 from datetime import datetime dateString = "15/12/2021" dateFormatter = "%d/%m/%Y" print(datetime.strptime(dateString, dateFormatter)) y = 1999 m = 2 d = 1 the_day = datetime(y,m,d) print(f"{the_day:%Y/%m/%d}")