作者Hsins (迅雷不及掩耳盜鈴)
看板Python
標題Re: [問題] 想請問如何不print出空格?
時間Sat Sep 17 12:59:22 2022
: 推 tzouandy2818: print("Name:" + str(name)) 09/16 22:25
: → tzouandy2818: 不知道用逗號跟轉字串連接差在哪 不過應該還是f-str 09/16 22:25
: → tzouandy2818: ing比較好 09/16 22:25
稍微展開來說說,關於使用逗號、加號
以及 f-string 一些容易混淆的地方。
首先來試試以下的程式:
>>> str1 = "Hello"
>>> str2 = "World!"
>>> print(str1, str2)
Hello World!
>>> print(str1 + str2)
HelloWorld!
>>> print((str1, str2)*3)
('Hello', 'World!', 'Hello', 'World!', 'Hello', 'World!')
>>> print((str1 + str2)*3)
HelloWorld!HelloWorld!HelloWorld!
在這個例子可以「猜」出來:
1. 使用逗號時,具體的操作其實是傳遞
兩個引數 str1 與 str2 給 print()
被放置在 tuple 中保持順序
2. 使用加號時,是將字串經過連結之後
的結果(一個新的字串)傳遞下去
CPython 直譯器在執行程式時,會先將其
翻譯成一系列的位元組碼(byte code),
我們可以透過 dis 來分析一下究竟他們
做了些什麼:
>>> import dis
>>> def fun1(str1, str2): return str1, str2
>>> def fun2(str1, str2): return str1 + str2
>>> dis.dis(fun1)
2 0 LOAD_FAST 0 (str1)
2 LOAD_FAST 1 (str2)
4 BUILD_TUPLE 2
6 RETURN_VALUE
>>> dis.dis(fun2)
2 0 LOAD_FAST 0 (str1)
2 LOAD_FAST 1 (str2)
4 BINARY_ADD
6 RETURN_VALUE
這樣是不是更清楚了一些?
---
至於原生字串與 f-string 的差異,我們
來看看 PEP 498 裡怎麼說的:
Regular strings are concatenated at
compile time, and f-strings are
concatenated at
run time.
[REF]
https://hhp.li/ZDsgG
讓我們多分析一個函數:
>>> def fun3(str1, str2): return f'{str1} {str2}'
>>> dis.dis(fun3)
2 0 LOAD_FAST 0 (str1)
2 FORMAT_VALUE 0
4 LOAD_CONST 1 (' ')
6 LOAD_FAST 1 (str2)
8 FORMAT_VALUE 0
10 BUILD_STRING 3
12 RETURN_VALUE
大概是這樣,至於實際上開發時要怎麼選擇
,我認為這個沒有標準答案。多數的情況下
我會選擇使用 f-string 處理,因為相較於
加號來說,寫起來更具可讀性,並且能夠處
理不同資料型別的輸入。
關於效率的差異,可以用 timeit 去做測量
,當然他的結果會根據使用的機器有所不同
:
>>> from timeit import timeit
>>> timeit('str1 + str2', setup='str1, str2 = "Hello", "World"')
0.06561679998412728
>>> timeit('f"{str1} {str2}"', setup='str1, str2 = "Hello", "World"')
0.09325840001110919
建議把引數數量增添到三個、四個、五個再
做一次測試,懶得自己測試就看一下別人的
測試結果:
String concatenation with + vs. f-string
[REF]
https://hhp.li/bZH9Q
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.141.109.67 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1663390765.A.E1C.html
推 tzouandy2818: 感謝補充 09/17 13:26
→ tzouandy2818: 雖然本來想說用Python就不要在計較效率了 可是看到 09/17 13:27
→ tzouandy2818: 效率差那麼多 又忍不住想計較 09/17 13:27
推 lycantrope: fstring 跟concat功能差很多,本來就不能單純比效能。 09/17 14:03
→ Hsins: 實際上效能差異並沒有特別顯著啦.... 09/17 14:06
推 vic147569az: 感謝H大開示 09/17 14:12
推 lycantrope: 沒錯,而且大部分時候concat都比較慢 09/17 14:34
→ Hsins: 通常 f'{var}' 也比 str(var) 要來的快,後者多了一個呼叫 09/17 14:41
→ Hsins: 函數的操作,一樣可以透過 dis 來做確認 09/17 14:41
推 Schottky: 推 09/17 17:16
推 cloki: 推 09/19 01:36