""",包含換行字元long_string = """
this is a long
string
"""
# this is a long
# string
(),不包含換行字元long_string = (
"this is a long "
"string"
)
# this is a long string
\,不包含換行字元long_string = "this is a long "\
"string"
# this is a long string
通常對於一些數字比較有格式需求,也就是 : 或是 % 後面的一些參數表示
簡易版:{:m.nf}
m:佔用的寬度n:小數點精度保留位數f:f 表示浮點、另外 d 表示整數、 e 表示科學記號複雜版:{:[[fill]align] [sign] [width] ["." precision] [type]}(使用空格作區隔,實際無空格)
[[fill]align]:在有設定 width 的條件下進行對齊
align:< 向左對齊(一般預設)、> 向右對齊(數字預設)、^ 置中對齊fill:填滿 width 的字元,預設是空格[sign]:+ 顯示 +正數或 -負數、-(預設)負數才顯示 -
[width]:佔用的最小總寬度["." precision] [type]:
precision 就是精度,會因為後面 type 而變動,若為 f 則為小數點後保留位數;但若為 g 時,則為小數點前後顯示幾位;s 的話則是保留多少長度;對整數 d 來說是不適用的type 同上面的 f 說明,g 表示 General,未填會依照內容作判斷f-strings{} 來表示變數或表達式value = 2
f"x = {value}"
# "x = 2"
f"x = {value + 1}"
# "x = 3"
w = {"name": "Tom", "mail": "abc@mail"}
f'name: {w["name"]}, mail:{w["mail"]}'
# name: Tom, mail:abc@mail
a = 3.1415
f"a is {a:{10}.{3}}" # type 未指定,會變成 g
f"a is {a:{10}.{3}f}" # type 指定 f
f"a is {a:0{10}.{3}f}" # 以 0 補滿
f"a is {a:<{10}.{3}f}" # 向左靠齊
f"a is {a:^{10}.{3}f}" # 置中
f"a is {a:+{10}.{3}f}" # 顯示 +
# a is 3.14
# a is 3.142
# a is 000003.142
# a is 3.142
# a is 3.142
# a is +3.142
b = 1543.1451
f"b is {b:{10}.{3}}" # type 未指定,會變成 g
f"b is {b:{10}.{3}f}" # type 指定 f
# b is 1.54e+03
# b is 1543.145
小補充
= 來拼接結果x = 1
f"{x+1=}" # Python 3.8
# x+1=2
format()" {:格式} {:格式}".format(參數, 參數)
"{:.2f}".format(3.1415926))
# 3.14
x = 1
y = 2
sum = x + y
"The sum of {} + {} is {}".format(x, y, sum)
"The sum of {1} + {0} is {2}".format(x, y, sum) # 指定順序
"The sum of {y} + {x} is {sum}".format(x=x, y=y, sum=sum) # 指定變數
# The sum of 1 + 2 is 3
# The sum of 2 + 1 is 3
# The sum of 2 + 1 is 3
%% 來替換指定位置的內容,需指定格式,格式錯就會出問題" %d " % (10)
- 來代表向左靠齊pi = 3.141592
"The value of %s is %-8.4f" %("pi", pi)
# The value of pi is 3.1416 .
來聊聊最常用的 list 吧!