欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中格式化字符串的四種實(shí)現(xiàn)

 更新時間:2020年05月26日 11:57:06   作者:TakingCoding4Granted  
這篇文章主要介紹了Python中格式化字符串的四種實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

關(guān)于Python的格式化字符串,幾乎所有接觸過Python語言的人都知道其中一種,即使用運(yùn)算符%,但對于絕大多數(shù)初學(xué)者來說也僅此而已。

因此,本文將先總結(jié)如何通過%運(yùn)算符來格式化字符串,同時指出這種方式的缺點(diǎn),然后帶你了解Python中另外三種強(qiáng)大的格式化字符串的方式:str.format()、f-string以及模板字符串,并給出在何時選擇何種方式的建議。

一、%運(yùn)算符格式化字符串

1. 如何使用

字符串對象都有一個使用%運(yùn)算符完成的內(nèi)置操作,可被用來格式化字符串。最簡單的如:

In [11]: name = "Monty Python"
In [12]: "Hello, %s." % name
Out[12]: 'Hello, Monty Python.'

如果想要對一段字符串中插入多個變量進(jìn)行格式化,則需要使用一個元組將待插入變量包在一起,如:

In [14]: name = "Monty Python"

In [15]: age = 100

In [16]: "Hello, %s. You are %d years old" % (name, age)
Out[16]: 'Hello, Monty Python. You are 100 years old'

2. 缺點(diǎn)概述

使用%運(yùn)算符的方式來格式化字符串自Python語言誕生之日起就已存在,上述代碼看起來也很直觀易讀,但是當(dāng)字符串更長,待插入變量更多,則使用%來格式化字符串的可讀性將急劇下降,如:

In [23]: first_name = "Eric"

In [24]: last_name = "Idle"

In [25]: age = 100

In [26]: profession = "comedian"

In [27]: affiliation = "Monty Python"

In [28]: "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
Out[28]: 'Hello, Eric Idle. You are 100. You are a comedian. You were a member of Monty Python.'

上述使用%格式化字符串不僅冗長,而且容易出錯,因?yàn)檫@種方式并不夠正確顯示元組或者字典。

實(shí)際上,在Python官方文檔中,對于使用%運(yùn)算符格式化字符串這種方式的評價也是負(fù)面的:

  • The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).使用%格式化字符串會產(chǎn)生一系列異常,這些異常將引起一系列常見錯誤(如:無法正確顯示元組和字典)。
  • Using the newerformatted string literals, the str.format() interface, ortemplate strings may help avoid these errors.
  • 使用更新的格式化字符串字面量(f-string:formatted string literals),str.format()接口或者模板字符串(template strings)可以幫助避免這些錯誤。

Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.
當(dāng)然,上述三種可替代的格式化字符串方式也都在簡潔、靈活和可擴(kuò)展方面有所取舍。

二、str.format()格式化字符串

1. 如何使用

str.format()是對使用%實(shí)現(xiàn)格式化字符串的一種改進(jìn)。這種方式使用的語法和普通函數(shù)調(diào)用相差無幾。

使用str.format(),字符串中待替換的域使用{}表示:

In [29]: name = "Eric"

In [30]: age = 100

In [31]: "Hello, {}. You are {}.".format(name, age)
Out[31]: 'Hello, Eric. You are 100.'

也可以通過索引的方式指定format()中哪一個變量和值應(yīng)該填入哪一個{},如:

In [32]: name = "Eric"

In [33]: age = 100

In [34]: "Hello, {1}. You are {0}.".format(age, name)
Out[34]: 'Hello, Eric. You are 100.'

除了索引,也可以通過在{}中指定名稱的方式來實(shí)現(xiàn)類似上述功能,如:

In [36]: name = "Eric"

In [37]: age = 100

In [38]: "Hello, {name}. You are {age}.".format(age=age, name=name)
Out[38]: 'Hello, Eric. You are 100.'

基于上面的方式,當(dāng)待格式化的信息都來自一個字典時,Python中還有如下騷操作:

In [39]: person = {'name': 'Eric', 'age': 100}

In [40]: "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
Out[40]: 'Hello, Eric. You are 100.'

更騷的是,上面的騷操作還能利用字典拆包**進(jìn)一步簡化:

In [41]: person = {'name': 'Eric', 'age': 100}

In [42]: "Hello, {name}. You are {age}.".format(**person)
Out[42]: 'Hello, Eric. You are 100.'

2. 缺點(diǎn)概述

相較于%運(yùn)算符方式,使用str.format()已經(jīng)使得格式化字符串語法更加可讀,但是當(dāng)變量增多時,這種方式寫出的程序也會顯得很冗長:

In [43]: first_name = "Eric"

In [44]: last_name = "Idle"

In [45]: age = 74

In [46]: profession = "comedian"

In [47]: affiliation = "Monty Python"

In [48]: print(("Hello, {first_name} {last_name}. You are {age}. " +
  ...: "You are a {profession}. You were a member of {affiliation}.") \
  ...: .format(first_name=first_name, last_name=last_name, age=age, \
  ...: profession=profession, affiliation=affiliation))
Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.

三、f-string格式化字符串

在Python 3.6中f-string被引入(具體請見PEP 498),也被稱作格式化字符串字面量(formatted string literals)。

f-string是字符串字面量,且其以字母f開頭,{}中包含變量或表達(dá)式,變量或表達(dá)式將在運(yùn)行(runtime)時通過使用__format__協(xié)議被替換成具體的值。

1. 如何使用

簡單的f-string格式化字符串如:

In [49]: name = "Eric"

In [50]: age = 100

In [51]: f"Hello, {name}. You are {age}."
Out[51]: 'Hello, Eric. You are 100.'

如前所述,{}中除接受變量外,還接受表達(dá)式,如:

In [52]: f"{2 * 37}"
Out[52]: '74'

f-string更強(qiáng)大的地方在于,{}中接受函數(shù)調(diào)用:

In [53]: def to_lowercase(input):
  ...:   return input.lower()
  ...: 

In [54]: name = "Eric Idle"

In [55]: f"{to_lowercase(name)} is funny."
Out[55]: 'eric idle is funny.'

甚至,你可以對創(chuàng)建于類的對象使用f-string,如:

class Comedian:
  def __init__(self, first_name, last_name, age):
    self.first_name = first_name
    self.last_name = last_name
    self.age = age

  def __str__(self):
    return f"{self.first_name} {self.last_name} is {self.age}."

  def __repr__(self):
    return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"


def main():
  new_comedian = Comedian("Eric", "Idle", "74")
  print(f"{new_comedian}")


if __name__ == '__main__':
  main()

上述代碼的輸出為:

Eric Idle is 74.

四、Template類格式化字符串

http://www.dbjr.com.cn/article/155119.htm

五、參考資料

[1] Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
[2] Python String Formatting Best Practices

到此這篇關(guān)于Python中格式化字符串的四種實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python格式化字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論