当前位置: 首页 > 面试题库 >

格式化字符串与串联

国言
2023-03-14
问题内容

我看到许多人使用这样的格式字符串:

root = "sample"
output = "output"
path = "{}/{}".format(root, output)

而不是像这样简单地串联字符串:

path = root + '/' + output

格式字符串是否具有更好的性能,还是仅用于外观?


问题答案:

这只是为了外观。您可以一眼看出格式是什么。我们中的许多人都比微优化更喜欢可读性。

让我们看看IPython的意思%timeit

Python 3.7.2 (default, Jan  3 2019, 02:55:40)
IPython 5.8.0
Intel(R) Core(TM) i5-4590T CPU @ 2.00GHz

In [1]: %timeit root = "sample"; output = "output"; path = "{}/{}".format(root, output)
The slowest run took 12.44 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 5: 223 ns per loop

In [2]: %timeit root = "sample"; output = "output"; path = root + '/' + output
The slowest run took 13.82 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 5: 101 ns per loop

In [3]: %timeit root = "sample"; output = "output"; path = "%s/%s" % (root, output)
The slowest run took 27.97 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 5: 155 ns per loop

In [4]: %timeit root = "sample"; output = "output"; path = f"{root}/{output}"
The slowest run took 19.52 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 5: 77.8 ns per loop


 类似资料:
  • 问题内容: 我正在开发一个应用程序,在其中执行一些请求以获取对象ID。在它们每个之后,我调用一个方法()将此id作为参数传递(请参见下面的代码)。 可以注意到,我正在将其转换为前缀并将其与前缀连接。但是,我知道我能做到这一点的多种其他方式(或者,例如),并在我的问题的结果:将超过字符串连接更好的可读性,代码约定和效率方面? 谢谢 问题答案: 这很容易成为基于意见的主题,但是我发现格式在大多数情况下

  • 主要内容:指定最小输出宽度,指定对齐方式,指定小数精度我们在《 第一个Python程序——在屏幕上输出文本》中讲到过 print() 函数的用法,这只是最简单最初级的形式,print() 还有很多高级的玩法,比如格式化输出,这就是本节要讲解的内容。 熟悉C语言 printf() 函数的读者能够轻而易举学会 Python print() 函数,它们是非常类似的。 print() 函数使用以 开头的转换说明符对各种类型的数据进行格式化输出,具体请看下表。

  • Parameter Position参数位置 Type参数类型 Required必需 Default默认 Description描述 1 string Yes n/a This is what format to use. (sprintf) 使用的格式化方式 This is a way to format strings, such as decimal numbers and such. Us

  • Go对字符串格式化提供了良好的支持。下面我们看些常用的字符串格式化的例子。 package main import "fmt" import "os" type point struct { x, y int } func main() { // Go提供了几种打印格式,用来格式化一般的Go值,例如 // 下面的%v打印了一个point结构体的对象的值 p := p

  • 3.5. 格式化字符串 Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式, 但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。 在 Python 中, 字符串格式化使用与 C 中 sprintf 函数一样的语法。 例 3.21. 字符串的格式化 >>> k = "uid" >>> v = "sa" >>> "%s=%s" % (k, v) 'uid=s

  • 由来 我一直对Slf4j的字符串格式化情有独钟,通过{}这种简单的占位符完成字符串的格式化。于是参考Slf4j的源码,便有了StrFormatter。 StrFormatter.format的快捷使用方式为StrUtil.format,推荐使用后者。 使用 //通常使用 String result1 = StrFormatter.format("this is {} for {}", "a", "