摘要:在之前,字符串格式化方法主要有兩種格式化和。使用較新的格式化字符串文字或可以有助于避免這些錯(cuò)誤。這些替代方案還提供了更強(qiáng)大,靈活和可擴(kuò)展的格式化文本方法。的使用是對(duì)格式化的改進(jìn),它使用普通函數(shù)調(diào)用語法,并且可以通過方法為對(duì)象進(jìn)行擴(kuò)展。
Python 3.6 提供了一種新的字符串格式化方法:f-strings,不僅比其他格式化方式更易讀,更簡(jiǎn)潔,更不容易出錯(cuò),而且它們也更快!
看完本文后,你將了解如何以及為何要使用 f-strings。
首先,我們先了解下現(xiàn)有的字符串格式化方法。
在 Python 3.6 之前,字符串格式化方法主要有兩種:%格式化 和 str.format()。下面我們簡(jiǎn)單看下它們的使用方法,以及局限。
1 %-格式化% 格式化方法從 Python 剛開始時(shí)就存在了,堪稱「一屆元老」,但是 Python 官方文檔中并不推薦這種格式化方式:
這里描述的格式化操作容易表現(xiàn)出各種問題,導(dǎo)致許多常見錯(cuò)誤(例如無法正確顯示元組和字典)。1.1 如何使用 %格式化
使用較新的格式化字符串文字或 str.format() 可以有助于避免這些錯(cuò)誤。這些替代方案還提供了更強(qiáng)大,靈活和可擴(kuò)展的格式化文本方法。
一般使用方式,要插入多個(gè)變量的話,必須使用元組:
>>> name = "hoxis" >>> age = 18 >>> "hello, %s. you are %s ?" %(name, age) "hello, hoxis. you are 18 ?"1.2 %格式化的缺陷
上面的代碼示例看起來還能讀,但是,一旦開始使用多個(gè)參數(shù)和更長的字符串,你的代碼將很快變得不那么容易閱讀:
>>> name = "hoxis" >>> age = 18 >>> country = "China" >>> hair = "black" >>> "hello, %s. you are %s ?. Your country is %s, and your hair is %s" %(name, age, country,hair) "hello, hoxis. you are 18 ?. Your country is China, and your hair is black"
可以看出,這種格式化并不是很好,因?yàn)樗苋唛L并且容易導(dǎo)致錯(cuò)誤,比如沒有正確顯示元組或字典。
不過還好我們還有 str.format()。
2 str.format()Python 2.6 中引入了 str.format() 格式化方法:https://docs.python.org/3/lib...。
2.1 str.format() 的使用str.format() 是對(duì) %格式化 的改進(jìn),它使用普通函數(shù)調(diào)用語法,并且可以通過 __format__() 方法為對(duì)象進(jìn)行擴(kuò)展。
使用 str.format() 時(shí),替換字段用大括號(hào)進(jìn)行標(biāo)記:
>>> "hello, {}. you are {}?".format(name,age) "hello, hoxis. you are 18?"
并且可以通過索引來以其他順序引用變量:
>>> "hello, {1}. you are {0}?".format(age,name) "hello, hoxis. you are 18?"
或者可以這樣:
>>> "hello, {name}. you are {age1}?".format(age1=age,name=name) "hello, hoxis. you are 18?"
從字典中讀取數(shù)據(jù)時(shí)還可以使用 **:
>>> person = {"name":"hoxis","age":18} >>> "hello, {name}. you are {age}?".format(**person) "hello, hoxis. you are 18?"
確實(shí),str.format() 比 %格式化高級(jí)了一些,但是它還是有自己的缺陷。
2.2 str.format() 的缺陷在處理多個(gè)參數(shù)和更長的字符串時(shí)仍然可能非常冗長,麻煩!看看這個(gè):
>>> "hello, {}. you are {} ?. Your country is {}, and your hair is {}".format(name, age, country,hair) "hello, hoxis. you are 18 ?. Your country is China, and your hair is black"3 f-Strings
還好,現(xiàn)在我們有了 f-Strings,它可以使得字符串格式化更加容易。
f-strings 是指以 f 或 F 開頭的字符串,其中以 {} 包含的表達(dá)式會(huì)進(jìn)行值替換。
下面從多個(gè)方面看下 f-strings 的使用方法,看完后,我相信你會(huì)對(duì)「人生苦短,我用 Python」有更深地贊同~
3.1 f-Strings 使用方法>>> name = "hoxis" >>> age = 18 >>> f"hi, {name}, are you {age}" "hi, hoxis, are you 18" >>> F"hi, {name}, are you {age}" "hi, hoxis, are you 18"
是不是很簡(jiǎn)潔?!還有更牛叉的!
因?yàn)?f-strings 是在運(yùn)行時(shí)計(jì)算的,那么這就意味著你可以在其中放置任意合法的 Python 表達(dá)式,比如:
運(yùn)算表達(dá)式
>>> f"{ 2 * 3 + 1}" "7"
調(diào)用函數(shù)
還可以調(diào)用函數(shù):
>>> def test(input): ... return input.lower() ... >>> name = "Hoxis" >>> f"{test(name)} is handsome." "hoxis is handsome."
也可以直接調(diào)用內(nèi)置函數(shù):
>>> f"{name.lower()} is handsome." "hoxis is handsome."
在類中使用
>>> class Person: ... def __init__(self,name,age): ... self.name = name ... self.age = age ... def __str__(self): ... return f"{self.name} is {self.age}" ... def __repr__(self): ... return f"{self.name} is {self.age}. HAHA!" ... >>> hoxis = Person("hoxis",18) >>> f"{hoxis}" "hoxis is 18" >>> f"{hoxis!r}" "hoxis is 18. HAHA!" >>> print(hoxis) hoxis is 18 >>> hoxis hoxis is 18. HAHA!
多行 f-string
>>> name = "hoxis" >>> age = 18 >>> status = "Python" >>> message = { ... f"hi {name}." ... f"you are {age}." ... f"you are learning {status}." ... } >>> >>> message {"hi hoxis.you are 18.you are learning Python."}
這里需要注意,每行都要加上 f 前綴,否則格式化會(huì)不起作用:
>>> message = { ... f"hi {name}." ... "you are learning {status}." ... } >>> message {"hi hoxis.you are learning {status}."}4 速度對(duì)比
其實(shí),f-string 里的 f 也許可以代表 fast,它比 %格式化方法和 str.format() 都要快:
from timeit import timeit print(timeit("""name = "hoxis" age = 18 "%s is %s." % (name, age)""", number = 10000)) print(timeit("""name = "hoxis" age = 18 "{} is {}.".format(name, age)""", number = 10000)) print(timeit("""name = "hoxis" age = 18 f"{name} is {age}."""", number = 10000))
運(yùn)行結(jié)果:
$ python3.6 fstring.py 0.002238000015495345 0.004068000009283423 0.0015349999885074794
很明顯,f-string 是最快的,并且語法是最簡(jiǎn)潔的,是不是迫不及待地要試試了?
5 注意事項(xiàng) 5.1 引號(hào)的處理可以在字符串中使用各種引號(hào),只要保證和外部的引號(hào)不重復(fù)即可。
以下使用方式都是沒問題的:
>>> f"{"hoxis"}" "hoxis" >>> f"{"hoxis"}" "hoxis" >>> f"""hoxis""" "hoxis" >>> f"""hoxis""" "hoxis"
那如果字符串內(nèi)部的引號(hào)和外部的引號(hào)相同時(shí)呢?那就需要 進(jìn)行轉(zhuǎn)義:
>>> f"You are very "handsome"" "You are very "handsome""5.2 括號(hào)的處理
若字符串中包含括號(hào) {},那么你就需要用雙括號(hào)包裹它:
>>> f"{{74}}" "{74}" >>> f"{{{74}}}" "{74}"
可以看出,使用三個(gè)括號(hào)包裹效果一樣。
當(dāng)然,你可以繼續(xù)增加括號(hào)數(shù)目,看下有什么其他效果:
>>> f"{{{{74}}}}" "{{74}}" >>> f"{{{{{74}}}}}" "{{74}}" >>> f"{{{{{{74}}}}}}" "{{{74}}}"
額,那么多括號(hào),看著有點(diǎn)暈了...
5.3 反斜杠上面說了,可以用反斜杠進(jìn)行轉(zhuǎn)義字符,但是不能在 f-string 表達(dá)式中使用:
>>> f"You are very "handsome"" "You are very "handsome"" >>> f"{You are very "handsome"}" File "", line 1 SyntaxError: f-string expression part cannot include a backslash
你可以先在變量里處理好待轉(zhuǎn)義的字符,然后在表達(dá)式中引用變量:
>>> name = ""handsome"" >>> f"{name}" ""handsome""5.4 注釋符號(hào)
不能在表達(dá)式中出現(xiàn) #,否則會(huì)報(bào)出異常;
>>> f"Hoxis is handsome # really" "Hoxis is handsome # really" >>> f"Hoxis is handsome {#really}" File "總結(jié)", line 1 SyntaxError: f-string expression part cannot include "#"
經(jīng)過以上的講解,是不是發(fā)現(xiàn) f-string 非常簡(jiǎn)潔實(shí)用、可讀性高,而且不易出錯(cuò),可以嘗試切換到 f-string 嘍~
f-string 也體現(xiàn)出了 Python 的奧義:
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren"t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you"re Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it"s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let"s do more of those!
如果覺得有用,歡迎關(guān)注我的微信,有問題可以直接交流,另外提供精品 Python 資料!
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/41975.html
摘要:合并日期和時(shí)間這個(gè)復(fù)合類名叫,是和的合體。截至目前,我們介紹的這些日期時(shí)間對(duì)象都是不可修改的,這是為了更好地支持函數(shù)式編程,確保線程安全,保持領(lǐng)域模式一致性而做出的重大設(shè)計(jì)決定。 新的日期和時(shí)間API Java的API提供了很多有用的組件,能幫助你構(gòu)建復(fù)雜的應(yīng)用。不過,Java API也不總是完美的。我們相信大多數(shù)有經(jīng)驗(yàn)的程序員都會(huì)贊同Java 8之前的庫對(duì)日期和時(shí)間的支持就非常不理想...
摘要:輸出下標(biāo)和對(duì)應(yīng)的元素集合集合是無序的,集合中的元素是唯一的,集合一般用于元組或者列表中的元素去重。 python內(nèi)置的數(shù)據(jù)類型 showImg(https://segmentfault.com/img/bVbrz1j); Python3.7內(nèi)置的關(guān)鍵字 [False, None, True, and, as, assert, async, await, break, class, co...
格式化流 實(shí)現(xiàn)格式化的流對(duì)象是PrintWriter(字符流類)或PrintStream(字節(jié)流類)的實(shí)例。 你可能需要的唯一PrintStream對(duì)象是System.out和System.err(有關(guān)這些對(duì)象的更多信息,請(qǐng)參閱命令行中的I/O),當(dāng)你需要?jiǎng)?chuàng)建格式化的輸出流時(shí),請(qǐng)實(shí)例化PrintWriter,而不是PrintStream。 與所有字節(jié)和字符流對(duì)象一樣,PrintStream和Pri...
閱讀 1927·2021-09-22 10:02
閱讀 2008·2021-09-02 15:40
閱讀 2903·2019-08-30 15:55
閱讀 2372·2019-08-30 15:44
閱讀 3652·2019-08-30 13:18
閱讀 3285·2019-08-30 11:00
閱讀 2020·2019-08-29 16:57
閱讀 622·2019-08-29 16:41