python字串格式化

來源:互聯網
上載者:User

標籤:mic   sig   參數   color   int   UI   ros   ace   width   

%和轉換符之間的修飾符

  • - ,靠左對齊標誌,預設為靠右對齊
  • +,顯示數值符號
  • 0,零填充
  • 一個指定最小寬度的數
  • .  一個小數點,後面跟位元(字串最大個數,浮點之後的位元,整數最小位元)
  • * 用於替換欄位寬度
1 print(‘%*.*f‘ % (10, 2, 3.14159))2 print(‘%.4s, %.5d, %.3f‘ % (‘hello‘, 16, 3.14159))3 print(‘%(key)010d, %(name)10s‘ % {‘key‘:123, ‘name‘:‘Ron‘})4 5 #vars()函數技巧6 name = ‘Ron‘7 age = 258 print(‘%(name)s is %(age)+d years old‘ % vars())

進階字串格式化s.format

  • {n} n為整數:被位置參數代替
  • {name}:被關鍵字參數代替
  • {{}}:輸出{}
  • {name[n]}:序列尋找
  • {name[key]}:字典尋找
  • {name.attr}:屬性尋找
  • {place:format_spec}:指定格式
    • [fill[align][sign][0][width][.precision][type]]
    • <,^,>:左中靠右對齊

 

 1 print("{0},{1},{0}".format(‘hello‘, ‘world‘)) 2 print("{name}, {age}".format(age=25, name=‘Ron‘)) 3 print(‘{0}, {age}‘.format(‘hello‘, age=22)) 4 print(‘{{hello}}, {}‘.format(123)) 5 print(‘{name[1]}‘.format(name=[1,2,3])) 6 print(‘{name[key]}‘.format(name={‘key‘:‘hello‘})) 7 print(‘{0.__doc__}‘.format(str)) 8 print("{0.real} {0.imag}".format(3 + 4j)) 9 print("{name:>8},{age:*^8d}, {high:8.2f}".format(name=‘Ron‘, age=25, high=176.567))10 11 x = 42; y = 3.1415912 print(‘{0:010b}‘.format(x))13 print(‘{0:010x}‘.format(x))14 print(‘{0:+010.2f}‘.format(y))15 print(‘{0:<+10.2%}‘.format(y))16 print(‘{0:{width}.{pre}f}‘.format(y, width=10, pre=3))17 print(‘{0!r:^20}‘.format(‘Guido‘))

 

python字串格式化

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.