作者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://webptt.com/cn.aspx?n=bbs/Python/M.1663390765.A.E1C.html
1F:推 tzouandy2818: 感谢补充 09/17 13:26
2F:→ tzouandy2818: 虽然本来想说用Python就不要在计较效率了 可是看到 09/17 13:27
3F:→ tzouandy2818: 效率差那麽多 又忍不住想计较 09/17 13:27
4F:推 lycantrope: fstring 跟concat功能差很多,本来就不能单纯比效能。 09/17 14:03
5F:→ Hsins: 实际上效能差异并没有特别显着啦.... 09/17 14:06
6F:推 vic147569az: 感谢H大开示 09/17 14:12
7F:推 lycantrope: 没错,而且大部分时候concat都比较慢 09/17 14:34
8F:→ Hsins: 通常 f'{var}' 也比 str(var) 要来的快,後者多了一个呼叫 09/17 14:41
9F:→ Hsins: 函数的操作,一样可以透过 dis 来做确认 09/17 14:41
10F:推 Schottky: 推 09/17 17:16
11F:推 cloki: 推 09/19 01:36