python3----字串格式化(format)

來源:互聯網
上載者:User

標籤:字串格式化   [1]   通過   關鍵字   千分位   進位   二進位   form   name   

用法:

  它通過{}和:來代替傳統%方式

1、使用位置參數

要點:從以下例子可以看出位置參數不受順序約束,且可以為{},只要format裡有相對應的參數值即可,參數索引從0開,傳入位置參數列表可用*列表

1 >>> li = [‘hoho‘,18]2 >>> ‘my name is {} ,age {}‘.format(‘hoho‘,18)3 ‘my name is hoho ,age 18‘4 >>> ‘my name is {1} ,age {0}‘.format(10,‘hoho‘)5 ‘my name is hoho ,age 10‘6 >>> ‘my name is {1} ,age {0} {1}‘.format(10,‘hoho‘)7 ‘my name is hoho ,age 10 hoho‘8 >>> ‘my name is {} ,age {}‘.format(*li)9 ‘my name is hoho ,age 18‘

2、使用關鍵字參數

要點:關鍵字參數值要對得上,可用字典當關鍵字參數傳入值,字典前加**即可

1 >>> hash = {‘name‘:‘hoho‘,‘age‘:18}2 >>> ‘my name is {name},age is {age}‘.format(name=‘hoho‘,age=19)3 ‘my name is hoho,age is 19‘4 >>> ‘my name is {name},age is {age}‘.format(**hash)5 ‘my name is hoho,age is 18‘

3、填充與格式化

:[填充字元][對齊 <^>][寬度]

1 >>> ‘{0:*>10}‘.format(10)  ##靠右對齊2 ‘********10‘3 >>> ‘{0:*<10}‘.format(10)  ##靠左對齊4 ‘10********‘5 >>> ‘{0:*^10}‘.format(10)  ##置中對齊6 ‘****10****‘

4、精度與進位

 1 >>> ‘{0:.2f}‘.format(1/3) 2 ‘0.33‘ 3 >>> ‘{0:b}‘.format(10)    #二進位 4 ‘1010‘ 5 >>> ‘{0:o}‘.format(10)     #八進位 6 ‘12‘ 7 >>> ‘{0:x}‘.format(10)     #16進位 8 ‘a‘ 9 >>> ‘{:,}‘.format(12369132698)  #千分位格式化10 ‘12,369,132,698‘

5、使用索引

1 >>> li2 [‘hoho‘, 18]3 >>> ‘name is {0[0]} age is {0[1]}‘.format(li)4 ‘name is hoho age is 18

 

python3----字串格式化(format)

聯繫我們

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