python学习笔记——基础篇(2):print输出

该系列用于记录自己学习python的过程。

运行环境:windows, python2.7

print是python最常用的输出手段,可以用它输出字符串,各种变量,也可以用来做格式化输出。

废话不多少,直接上代码,对比下面代码的输出结果,就可以对print的输出有基本的理解了。

# -*- coding:utf-8 -*-
# sample for print
print "some string"
print 'some string'
print "I said: 'you can!'"
print "I said: 'you can't!'"
print 123
print True

# this is a comment
# format 
print "%d" % 123
print "%s" % "123"
print "%f" % (1.0/3)
print "%10.3f" % (1.0/3)
#-10.3,左对齐,10个占位符,小数点后三位精度
print "%-10.3f" % (1.0/3)
# bool变量输出
print "%d" % True
print "%r" % True
# %r 与 %s 
print "%s" % "I \t am a string.\n"
print "%r" % "I \t am a string.\n"
#多个变量格式化输出
print "%d %s" % (100,'some string')
# 一行输出
print "half of a line ,",
print "another half of a line."

这段代码应该有如下输出:

some string
some string
I said: 'you can!'
I said: 'you can't!'
123
True
123
123
0.333333
     0.333
0.333
1
True
I        am a string.

'I \t am a string.\n'
100 some string
half of a line , another half of a line.

python格式化输出

  1. python的格式化输出和C语言类似,主要有以下几种

formatter

var

%d,%o,%x

十进制,八进制,十六进制

%s

字符串

%[-]m.n f

%-10.3f,左对齐,10个占位符,3位小数精度浮点数输出

%r

raw 输出

2. raw输出是什么鬼?
参考上面的代码,对比%r和%s的输出的不同,可知%r将不会对字符串做任何转换,包括对bool变量值的转换和对转移字符的转换,它将字符串最原始的内容输出出来。
3. 还有没有其他的格式化输出方式?
还可以使用format输出,类似于c#,如下

>>> "{0} is {1} years old".format("Tom",12)
'Tom is 12 years old'

具体可参考python document:Advanced String Formatting

参考: