Python 中格式化字串 % 和 format 兩種方法之間的區別

來源:互聯網
上載者:User

標籤:特性   參數   class   his   code   href   指定   屬性   列表   

  Python2.6引入了 format 格式化字串的方法,現在格式化字串有兩種方法,就是 % 和 format ,具體這兩種方法有什麼區別呢?請看以下解析。

# 定義一個座標值c = (250, 250)# 使用%來格式化s1 = "敵人座標:%s" % c

 

上面的代碼很明顯會拋出一個如下的TypeError:

TypeError: not all arguments converted during string formatting

像這類格式化的需求我們需要寫成下面醜陋的格式才行:

 

# 定義一個座標值c = (250, 250)# 使用%醜陋的格式化...s1 = "敵人座標:%s" % (c,)

 

而使用 format 就不會存在上面的問題:

# 定義一個座標值c = (250, 250)# 使用format格式化s2 = "敵人座標:{}".format(c)

一般情況下,使用 % 已經足夠滿足我們的需求,但是像這種一個位置需要添加元素或清單類型的,就最好選擇 format 方法。

新特性

在Python3.6中加入了f-strings:

In[1]: name = "Q1mi"In[2]: age = 18In[3]: f"My name is {name}.I‘m {age}"Out[3]: "My name is Q1mi.I‘m 18"
format 的常用方法

通過位置(索引)

In[1]: data = ["Q1mi", 18]In[2]: "Name:{0}, Age:{1}".format(*data)Out[2]: ‘Name:Q1mi, Age:18‘


通過關鍵字

In[1]: data = {"name": "Q1mi", "age": 18}In[2]: "Name:{name}, Age:{age}".format(**data)Out[2]: ‘Name:Q1mi, Age:18‘

通過對象屬性

In[1]: class Person(object):   ...:     def __init__(self, name, age):   ...:         self.name = name   ...:         self.age = age   ...:     def __str__(self):         ...:         return "This guy is {self.name}, {self.age} years old.".format(self=self)   ...:     In[2]: p = Person("Q1mi", 18)In[3]: str(p)Out[3]: ‘This guy is Q1mi, 18 years old.‘


通過下標

In[1]: "{0[0]} is {0[1]} years old.".format(data)Out[1]: ‘Q1mi is 18 years old.‘

填充與對齊

填充常跟對齊一起使用

^  <  >  分別是置中、靠左對齊、靠右對齊,後面頻寬度。

:號後面帶填充的字元,只能是一個字元,不指定的話預設是用空格填充。

In[1]: "{:>10}".format(‘18‘)Out[1]: ‘        18‘In[2]: "{:0>10}".format(‘18‘)Out[2]: ‘0000000018‘In[3]: "{:A>10}".format(‘18‘)Out[3]: ‘AAAAAAAA18

補充一個字串內建的 zfill() 方法:

Python zfill() 方法返回指定長度的字串,原字串靠右對齊,前面填充 0.

zfill() 方法文法:str.zfill(width)

參數width指定字串的長度。原字串靠右對齊,前面填充0

返回指定長度的字串

In[1]: "{:.2f}".format(3.1415926)Out[1]: ‘3.14‘


精度與類型f

 

精度常跟類型f一起使用。

In[1]: "{:.2f}".format(3.1415926)Out[1]: ‘3.14‘

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

其他進位

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

 

In[1]: "{:b}".format(18)Out[1]: ‘10010‘In[2]: "{:d}".format(18)Out[2]: ‘18‘In[3]: "{:o}".format(18)Out[3]: ‘22‘In[4]: "{:x}".format(18)Out[4]: ‘12‘

千位分隔字元

In[1]: "{:,}".format(1234567890)Out[1]: ‘1,234,567,890‘

 

Python 中格式化字串 % 和 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.