格式化字串format函數,字串format函數

來源:互聯網
上載者:User

格式化字串format函數,字串format函數

Format

 

一、文法

通過{} 和 : 來代替 %

二、案例

name = "bigberg"age = 18msg1="my name is {},and my age is {}.".format(name,age)msg2="my name is {0},and my age is {1}.".format(name,age)msg3="my name is {_name},and my age is {_age}.".format(_name=name,_age=age)msg4="my name is {1},and my age is {0},and my brother's age is {0}.".format(age,name)print(msg1)print(msg2)print(msg3)print(msg4)#輸出my name is bigberg,and my age is 18.my name is bigberg,and my age is 18.my name is bigberg,and my age is 18.my name is bigberg,and my age is 18,and my brother's age is 18.

  字串的format函數可以接受不限個參數,位置可以不按順序,可以不用或者用多次,不過2.6不可為空{},2.7以後才可以。

 

三、下標擷取元素

info = ["bigberg",18]msg='{0[0]},{0[1]}'.format(info)print(msg)#輸出bigberg,18

 

四、格式限定符

文法是 {:}

  1.填充與對齊

   填充和對齊常一起使用

  ^、<、>分別是置中 、靠左對齊、靠右對齊 ,後面頻寬度。 :後面帶填充的字元,只能是一個字元,不指定預設用空格填充。

number = 234print('{:>8}'.format(number))print('{:*>8}'.format(number))#輸出     234*****234 

  

  2.精度與類型f

num = 123.23423print('{:.2f}'.format(num))#輸出123.23

  其中 .2表示長度為2的精度,f 表示 float 類型

  

  3.進位

  b、d、o、x 分別表示 二進位、十進位、八進位和十六進位 

num = 25print('{:b}'.format(num))print('{:d}'.format(num))print('{:o}'.format(num))print('{:x}'.format(num))#輸出11001253119

  

聯繫我們

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