串联运算符+或, [英] Concatenation Operator + or ,

查看:72
本文介绍了串联运算符+或,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var1 = 'abc'
var2 = 'xyz'

print('literal' + var1 + var2) # literalabcxyz
print('literal', var1, var2) # literal abc xyz

...与,两者之间有什么区别?

... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest?

谢谢

推荐答案

(您使用的是Python 3.x,其中print是一个函数-在2.x中,print是一个语句。建议您使用主要的Python版本— 2.x或3.x—尤其是在询问时,最好提一下寻求帮助,因为目前大多数人都合理地假设使用2.x,除非另有说明。)

(You're using Python 3.x, where print is a function—in 2.x, print is a statement. It's a good idea to mention the major Python version—2.x or 3.x—especially when asking for help, because currently most people reasonably assume 2.x unless it's stated.)

第一个 print('literal'+ var1 + var2 ),计算一个表达式并传递单个参数进行打印。第二个 print('literal',var1,var2)仅传递三个参数进行打印。这几乎是偶然的几乎相同的输出:这就是打印的工作方式。第二种方法不做任何串联,只是输出每个用空格隔开的值(这是打印的默认行为)。

The first, print('literal' + var1 + var2), evaluates an expression and passes a single argument to print. The second, print('literal', var1, var2), just passes three arguments to print. This is almost the same output purely by chance: that's how print works. The second is not doing any concatenation, and is simply outputting each value separated by a space (which is print's default behavior).

要明确:表达式中的加号正在进行串联,但逗号未进行串联。

To be explicit: the plus in the expression is doing concatenation, but the comma is not doing concatenation.

计时:我得到了以下结果;但是,我认为这是有偏见的,因为字符串太短(例如,较长的字符串可能会颠倒结果),并且无论如何,打印问题中的内容不会花费很长时间(担心很多其他东西)。

Timing: I got the results below; however, I believe this is biased because the strings are so short (e.g. longer strings could reverse the result), and in any case, printing as presenting in the question won't take long (you'll get better performance worrying about many other things instead).

注意:使用 python -m timeit --help 了解有关如何使用timeit的说明。

Note: Use python -m timeit --help for instructions on how to use timeit.

$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, a, b'
100000 loops, best of 3: 7.68 usec per loop
$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, a + " " + b'
100000 loops, best of 3: 4.67 usec per loop
$ python -m timeit -s 'from cStringIO import StringIO; out = StringIO(); a = "abc"; b = "def"' 'print >>out, " ".join([a, b])'
100000 loops, best of 3: 5.37 usec per loop

尤其要注意,每个代码将给出完全相同的输出(如果一种方法给出的结果错误,则进行比较是毫无意义的>)。在这些测试中,StringIO是一种打印到屏幕的简单方法,但是它也可能会影响结果。

In particular, notice each code will give the exact same output (it's meaningless to compare if one method gives the wrong results). The StringIO is an easy way to not print to the screen in these tests, but it could be affecting the results too.

这篇关于串联运算符+或,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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