Python-print学习

>>> reply = """

Greetings...

Hello %(name)s!

Your age squared is %(age)s

"""

>>> values = {'name': 'Bob', 'age':40}

>>> print(reply % values)

 

Greetings...

Hello Bob!

Your age squared is 40

 

说明:

在预设语句中,可以直接填写%()表达式,格式化字符串,格式如下:

%[(name)][(flags)][width][.precision]typecode

其中"name"可以通过字典进行输出

 

==============================================================================

>>> template = '{0}, {1} and {2}'

>>> template.format{'spam', 'ham', 'eggs')

'spam, ham and eggs'

>>> template = '{motto}, {pork} and {food}‘

>>> template.format(motto='spam', pork='ham', food='eggs')

'spam, ham and eggs'

>>> template = '{motto}, {0} and {food}'

>>> template.format('ham', motto='spam', food='eggs')

'spam, ham and eggs'

 

说明:

通过.format形式,可以进行输出,注意{}中的指代,数字代表读取format中的位置,string型则代表指代变量

 

===============================================

>>> import sys

>>> 'My {1[spam]} runs {0.platform}'.format(sys, {'spam': 'laptop'})

'My laptop runs win32'

 

>>> 'My {config[spam]} runs {sys.platform}'.format(sys = sys, config={'spam': 'laptop'})

'My laptop runs win32'

 

说明:

可以使用键、属性和偏移量。

注意,在print语句中,填写的sys并不代表程序固定变量,需要通过sys=sys进行赋值

================================================

>>>'{0.platform:>10} = {1[item]:<10}'.format(sys, dict(item='laptop'))

'     win32 = laptop    '

{0.platform:>10} 意味着:“第一个参数”的“platform属性”在“10字符宽度”的字段中“右对齐”;

{1[item]:<10} 意味着,“第二个参数”的“[item]字段”在“10字符宽度”的字段中“左对齐”;

>>> '%-10s = %(item)-10s' % dict(plat=sys.platform, item='laptop')

'     win32 = laptop    '

================================================

 >>> '{:,.2f}'.format(296999.2567)

'296,999.26'

自动为替换目标分配,按照国际标准

================================================

print([object,……][,sep=' '][,end='\n'][,file=sys.stdout])

默认sep,end,file三个参数分别为‘一个单个的空格’,‘换行符’,‘sys.stdout输出’。不过可以自己添加:

sep为打印输出的object之间的分隔符;

end为打印输出的结尾;

file为打印输出的位置,带有一个类似文件的write(string)方法的任何对象都可以传递;

================================================

print重定向

import sys

sys.stdout = open('log.txt', 'a')      # Redirects prints to a file

……

print(x,y,x)                # Shows up in log.txt

由于sys.stdout已经被重定向为开启的log.txt文件,而print函数中的'file=sys.stdout',则自动重定向到该文件中,因此在运行print函数后,输出的内容自动写入log.txt文件末尾中

注1:甚至可以将sys.stdout重设为非文件的对象,只要该对象有预期的协议(write方法)即可。

注2:要记得在重定向后,要恢复初始sys.stdout指向。如下

temp = sys.stdout

sys.stdout = open('log.txt', 'a')

sys.stdout.close()

sys.stdout = temp

 

python 3.X中,可以通过file=X来重定向

log = open('log.txt', 'a')

print(x, y, file=log)

 

也可以通过打印标准错误流的方式

import sys

print(x, y, file=sys.stdeer)

=================================================

 

posted @ 2014-08-26 16:38  小龙酸菜  阅读(238)  评论(0编辑  收藏  举报