天天看點

format的幾種用法 Python中應該使用%還是format來格式化字元串?

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

%還是format

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

新特性

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

In[1]: name = "Q1mi"
In[2]: age = 18
In[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]: "18".zfill(10)
Out[1]: '0000000018'      

精度與類型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'      

轉載自 https://www.cnblogs.com/liwenzhou/p/8570701.html