我一直很好奇
为什么 python 有不同的打印方式?
例如
print "this is ",a," and " ,b
对比
print "this is %d and %d" %(a,b)
有任何性能问题吗?和东西?
最佳答案
在 Python 中也有很多“打印东西”的方法,包括更现代的 str.format()
方法、sys.stdout.write('foo')
,可能还有其他方法。
关于 print a, b, c
和 %
格式的区别,我一般使用前者主要用于调试输出,当你只需要 a 之间的空格时一堆变量。当我想要精确格式化或更多地控制格式化时,我使用 %
(实际上,这些天我总是使用 str.format
)。
例如:
print 'DEBUG:', var1, var2
对比:
print 'Benchmarks took {0:.3f}s to run'.format(seconds)
此外,%
和 str.format
格式更为通用——它们实际上不打印任何内容,它们返回一个字符串,您可以打印、写入到文件、存储在数据库中、作为网络响应发送等。
关于性能——别担心。这三者几乎肯定都很快,过早的优化是万恶之源。
我真的不想发布数字(因为这可能会鼓励错误的心态),但是 timeit
使用起来非常简单,我情不自禁。
C:\>python -m timeit -s "import cStringIO; s = cStringIO.StringIO()"
"print >>s, 'this is', 'a', 'test'"
100000 loops, best of 3: 3.39 usec per loop
c:\>python -m timeit -s "import cStringIO; s = cStringIO.StringIO()"
"print >>s, 'this is %s test' % 'a'"
1000000 loops, best of 3: 1.32 usec per loop
C:\>python -m timeit -s "import cStringIO; s = cStringIO.StringIO()"
"print >>s, 'this is {0} test'.format('a')"
1000000 loops, best of 3: 1.64 usec per loop
我不太清楚为什么 print a, b, c
方法明显变慢,这可能是一个实现细节。不过,请不要担心——打印到您的文件或屏幕所花费的时间可能远远超过字符串格式化部分。
关于python - 打印格式?哪个python更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12415327/