python span.string函数_【转】python f-string
主要內容
從Python 3.6開始,f-string是格式化字符串的一種很好的新方法。與其他格式化方式相比,它們不僅更易讀,更簡潔,不易出錯,而且速度更快!
在本文的最后,您將了解如何以及為什么今天開始使用f-string(后文稱為F字符串)。
但首先, 我們要聊以下在F字符串出現之前我們怎么實現格式化字符的。
舊時代的格式化字符串
在Python 3.6之前,有兩種將Python表達式嵌入到字符串文本中進行格式化的主要方法:%-formatting和str.format()。您即將看到如何使用它們以及它們的局限性。
Option #1: %-formatting
這是Python格式化的OG(original generation),伴隨著python語言的誕生。您可以在Python文檔中內容。請記住,文檔不建議使用%格式,其中包含以下注釋:
“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).
Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.”
怎樣使用 %-formatting
字符串對象具有使用%運算符的內置操作,您可以使用它來格式化字符串。以下是實踐中的情況:
1
2
name = "Eric"
"Hello, %s." % name
'Hello,?Eric.'
為了插入多個變量,您必須使用這些變量的元組。以下是你如何做到這一點:
1
2
3
name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)
'Hello,?Eric.?You?are?74.'
為什么 %-formatting不好用
上面剛剛看到的代碼示例足夠易讀。但是,一旦你開始使用幾個參數和更長的字符串,你的代碼將很快變得不太容易閱讀。事情已經開始顯得有點凌亂:
1
2
3
4
5
6
7
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
"Hello, %s %s. You are %s. You are a %s. You were a member of %s." %
總結
以上是生活随笔為你收集整理的python span.string函数_【转】python f-string的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: excel怎么设置别人只读(Excel怎
- 下一篇: python中模块的概念_Python中