Python之路--Python中應該使用%還是format來格式化字串?

來源:互聯網
上載者:User

標籤:hat   空格   問題:   htm   aaa   ring   存在   選擇   href   

一、%還是format1、%、format皇城PK

Python中格式化字串目前有兩種陣營:%和format,我們應該選擇哪種呢?

自從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了。

 

2、新特性

在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用法1、通過位置
In[1]: data = ["Q1mi", 18]In[2]: "Name:{0}, Age:{1}".format(*data)Out[2]: ‘Name:Q1mi, Age:18‘

 

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

 

3、通過對象屬性
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.‘

 

4、通過下標
In[1]: "{0[0]} is {0[1]} years old.".format(data)Out[1]: ‘Q1mi is 18 years old.‘

 

5、填充與對齊填充常跟對齊一起使用
  •  ^、<、>分別是置中、靠左對齊、靠右對齊,後面頻寬度
  •  :號後面帶填充的字元,只能是一個字元,不指定的話預設是用空格填充。
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]: "18".zfill(10)Out[1]: ‘0000000018‘

 

6、精度與類型f

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

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

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

 

7、其他進位

  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‘

 

8、千位分隔字元
In[1]: "{:,}".format(1234567890)Out[1]: ‘1,234,567,890‘

 

Python之路--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.