標籤:理解 string fill mat ict 保留 format 填充 意思
這是12月規劃的內容,2018年一月開篇~
如果有什麼錯誤,還請提出來~
格式化這個在print已經提到一點,說實話和C語言非常類似
%的方法:
%[(name)][flags][width].[precision]typecode
%c |
轉換成字元(ASCII 碼值,或者長度為一的字串) |
%r |
優先用repr()函數進行字串轉換 |
%s |
優先用str()函數進行字串轉換 |
%d / %i |
轉成有符號十進位數 |
%u |
轉成無符號十進位數 |
%o |
轉成無符號八位元 |
%x / %X |
轉成無符號十六進位數(x / X 代錶轉換後的十六進位字元的大小寫) |
%e / %E |
轉成科學計數法(e / E控制輸出e / E) |
%f / %F |
轉成浮點數(小數部分自然截斷) |
%g / %G |
%e和%f / %E和%F 的簡寫 |
%% |
輸出% (格式化字串裡麵包括百分比符號,那麼必須使用%%) |
%r和%s都是字串轉化,那麼區別呢
1 string = "Hello\tworld\n"2 print("%s"%string)3 print("%r"%string)4 Hello world str()得到的字串是面向使用者的5 6 ‘Hello\tworld\n‘ repr()得到的字串是面向機器的
而其他符號大多都見過,這裡不再說明
str.format()函數用"{}"和":"代替了以前的"%."符號。
[[fill]align][sign][#][0][width][,][.precision][type]
{}通過位置匹配參數,當然不寫預設順序,可以重複出現啦
*"abc"什麼意思要到函數才講了,這裡理解成*"abc"=‘a‘,‘b‘,‘c‘就成
1 print("{1},{0},{2}".format(*"abc"))2 print("{1},{2},{0}".format(‘a‘,‘b‘,‘c‘))
b,a,cb,c,a
{}通過名稱配置參數
1 print("{a},{b},{c}".format(a=1,b=‘s‘,c=4))
1,s,4
{}通過下標配置參數
1 alist=[‘s‘,2,‘c‘]2 print(‘{0[1]}‘.format(alist))
alist=[‘s‘,2,‘c‘]print(‘{0[1]}‘.format(alist))#2
以上也稱為映射list和dict
接下來就是一連串的 {:XXXXXX} 操作了
Python 字串格式化%與format() 函數 九