打印格式?哪一个更好python

Moh*_*hit 3 python

我一直很好奇

为什么python有不同的打印方式?

例如

print "this is ",a," and " ,b
Run Code Online (Sandbox Code Playgroud)

VS

print "this is %d and %d" %(a,b)
Run Code Online (Sandbox Code Playgroud)

任何性能问题?和东西?

Ben*_*oyt 5

还有很多方法可以在Python中"打印东西",包括更现代的str.format()方法sys.stdout.write('foo'),还有其他方法.

就格式print a, b, c%格式之间的差异而言,我通常使用前者主要用于调试输出,当你只需要一堆变量之间的空格时.当我想要格式化格式或对格式的更多控制时,我会使用%(实际上,这些天我总是使用str.format).

例如:

print 'DEBUG:', var1, var2
Run Code Online (Sandbox Code Playgroud)

与:

print 'Benchmarks took {0:.3f}s to run'.format(seconds)
Run Code Online (Sandbox Code Playgroud)

此外,%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
Run Code Online (Sandbox Code Playgroud)

我不太清楚为什么这种print a, b, c方法明显变慢,可能是一个实现细节.但是,不要担心 - 打印到文件或屏幕所需的时间可能远远超过字符串格式化部分.