%格式化和format格式化--python__python

來源:互聯網
上載者:User
<span style="font-family:FangSong_GB2312;font-size:18px;">格式符%[(name)][floags][width].[precision]typecode(name) 可選,用於選擇指定的keyflags  可選,可提供的值有:    · +    靠右對齊,整數前加正號,負數前加負號    · -    靠左對齊,正數錢無符號,負數前加負號;    · 空格 靠右對齊;正數前加空格,負數前加負號    · 0    靠右對齊,正數前無符號,負數前加負號;用0填充width   可選,佔有寬度typecode  必選%s 字串(str()的顯示)%r 字串採用repr()顯示%c 單個字元%b 二進位整數 bin%i 十進位整數 int%o  八進位整數 oct%x 十六進位整數 hex%f  浮點數%e 指數%% 字元% (前提是裡面要有格式符的話需要這麼寫)案例:a = "i am %s" % "alex"a = "i am %s age %d " % ("alex",18)a = "i am %(name)s age %(age)d" % {"name":"alex","age":18}a = "percent %.2f" % 99.98234a = "i am %(pp).2f" % {"pp":123.3245}a = "i am %.2f %%" % {"pp":123.3223455} format 格式化type         【可選】格式化類型 •傳入” 字串類型 “的參數 •s,格式化字串類型資料•空白,未指定類型,則預設是None,同s•傳入“ 整數類型 ”的參數•b,將10進位整數自動轉換成2進位表示然後格式化•c,將10進位整數自動轉換為其對應的unicode字元•d,十進位整數•o,將10進位整數自動轉換成8進位表示然後格式化;•x,將10進位整數自動轉換成16進位表示然後格式化(小寫x)•X,將10進位整數自動轉換成16進位表示然後格式化(大寫X)•傳入“ 浮點型或小數類型 ”的參數 •e, 轉換為科學計數法(小寫e)表示,然後格式化;•E, 轉換為科學計數法(大寫E)表示,然後格式化;•f , 轉換為浮點型(預設小數點後保留6位)表示,然後格式化;•F, 轉換為浮點型(預設小數點後保留6位)表示,然後格式化;•g, 自動在e和f中切換•G, 自動在E和F中切換•%,顯示百分比(預設顯示小數點後6位)還是看案例吧a = "i am {},age {}".format("seven",18,"alex")b = "i am {},age {}, {}".format(*["seven", 18 ,"alex"])c = "i am {0}, age {1}, really {0}".format("seven", 18)d = "i am {0}, age{1}, really {0}".format(*["seven", 18])e = "i am {name}, age {age}, really {name}".format(name="seven", age = 18)f = "i am {name}, age {age}, rally {name}".format(**{"name":"seven", "age":18})g = "i am {0[0]},age{0[1]}, really{0[2]}".format([1,2,3],[11,22,33])h = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 888.1)i = "i am {:s}, age {:d}".format(*["seven", 18])j = "i am {name:s}, age {age:d}".format(name="seven",age=18)k = "i am {name:s}, age {age:d}".format(**{"name":"seven","age":18})l = "numers:{:b},{:o},{d},{:x},{:X},{:%}".format(15,15,15,15,15,15.32445,2)m = "numbers:{0:b},{0:o},{0:d},{0:x},{0:%}".format(15)tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)更多格式化操作:https://docs.python.org/3/library/string.htmlhttp://www.cnblogs.com/wupeiqi/articles/5484747.html</span>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.