与“+"连接比用“,"分隔更有效什么时候使用打印? [英] Is concatenating with "+" more efficient than separating with "," when using print?

查看:39
本文介绍了与“+"连接比用“,"分隔更有效什么时候使用打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到,如果我在 print() 函数中使用 + 进行连接并在 shell 中运行代码,则文本显示得更快.然而,当使用 , 时,文本看起来要慢得多,就像正在输入"动画效果一样.

I just noticed that if I use + for concatenation in the print() function and run the code in the shell the text appears more quickly. Whereas, when using ,, the text appears much slower as if with a "being typed" animation effect.

这两者之间有效率差异吗?

Is there a efficiency difference between these two?

推荐答案

edit:似乎问题与其说是关于操作的性质,不如说是关于它们的速度,这在本答案中没有讨论!

edit: Seems the question was not so much about the nature of the operations as their speed, which is not discussed in this answer!

不同之处在于 + 使用连接来创建更大的字符串以传递给 print 函数,而使用 , 传递print 函数的多个字符串.请注意,这些行为对于 print 函数并不特殊:连接只是字符串上的一种方法,逗号始终用于分隔函数参数.

The difference is that with + you use concatenation to create a larger string to pass to the print function, while with , you pass multiple strings to the print function. Note that these behaviours are not special for the print function: concatenation is just a method on strings, and comma is always used to separate function arguments.

例如,使用串联:

print('hello' + ' ' + 'world')

这首先将三个字符串连接起来形成'hello world',然后打印出来.

This first concatenates the three strings to form 'hello world', and then prints that.

使用多个参数时:

print('hello', 'world')

这将两个字符串传递给 print 函数.正如您可以阅读此处printfunction 将一个或多个对象作为参数,并打印它们,它们由另一个参数 sep 分隔,默认情况下它是一个空格.因此,这会产生与前一个示例相同的输出.

This passes two strings to the print function. As you can read here, the print function takes one or multiple objects as arguments, and prints them separated by another argument, sep, which by default is a space. So this produces the same output as the previous example.

请注意,可以将任意数量的参数传递给 print 函数,并且这些参数本身可以是连接字符串:

Note that any number of arguments can be passed to the print function, and that these arguments in themselves can be concatenated strings:

print('i' + ' ' + 'want', 'to', 'print', 'some', 'strings')

好的部分是你可以指定 sep 参数来改变行为:

The nice part is that you can specify the sep argument to change the behaviour:

print('mary', 'peter', 'bob', sep=' and ')

结果:mary and peter and bob

这篇关于与“+"连接比用“,"分隔更有效什么时候使用打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆