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

來源:互聯網
上載者:User

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

1. format可以接受無限個的參數,位置可以不按順序:

In [1]: "{} {}".format("hello","world") #不設定位置,按預設順序Out[1]: 'hello world'In [2]: "{0} {1}".format("hello","world") #指定位置Out[2]: 'hello world'In [3]: "{1} {0} {1}".format("hello","world") #指定位置,重複使用參數Out[3]: 'world hello world'In [4]: "{name} {age}".format(name="Linda",age=15)#通過關鍵字Out[4]: 'Linda 15'# 通過字典設定參數In [5]: info = {"name":"Linda","age":15}In [6]: "{name} {age}".format(**info)Out[6]: 'Linda 15'# 通過列表設定參數In [7]: my_list = ['hello','world']In [8]: "{0[0]} {0[1]}".format(my_list)Out[8]: 'hello world'

2. format格式控制:文法是{}中帶冒號(:)

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

+ 表示在正數前顯示 +,負數前顯示 -;  (空格)表示在正數前加空格

b、d、o、x 分別是二進位、十進位、八進位、十六進位。

# 置中顯示,長度度為4In [9]: "{:^4}".format("he")Out[9]: ' he '# 靠左對齊,長度為4,空白地方填充"x"In [10]: "{:x<4}".format("he")Out[10]: 'hexx'# 顯示正負數符號In [11]: "{:+}".format(-3)Out[11]: '-3'# 8的二進位顯示In [12]: "{:b}".format(8)Out[12]: '1000'# 用大括弧{}轉義大括弧In [13]: "{} is {{0}}".format("hello")Out[13]: 'hello is {0}'

 

聯繫我們

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