作者:
Hsins (翔)
2022-09-17 12:59:22: 推 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
這樣是不是更清楚了一些?