楼主:
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
这样是不是更清楚了一些?