python2.7格式化输出_Python 2.7.X 开发文档-Python格式化输入与输出

Python 2.7提供了多种字符串格式化方法,包括使用表达式语句、print语句、str.format()方法和Template方法。str.format()方法提供更灵活的输出控制,如指定对齐方式、精度等。另外,旧式的%操作符也用于字符串格式化,类似于C语言的printf风格。
摘要由CSDN通过智能技术生成

7.1. 格式化输出

我们有两种大相径庭的输出值方法:表达式语句和 print 语句。(第三种方法是使用文件对象的 write() 方法,标准文件输出可以参考 sys.stdout,详细内容参见库参考手册。)

通常,你想要对输出做更多的格式控制,而不是简单的打印使用空格分隔的值。有两种方法可以格式化你的输出:第一种方法是由你自己处理整个字符串,通 过使用字符串切割和连接操作可以创建任何你想要的输出形式。string 类型包含一些将字符串填充到指定列宽度的有用操作,随后就会讨论这些。第二种方法是使用 str.format() 方法。

标准模块 string 包括了一些操作,将字符串填充入给定列时,这些操作很有用。随后我们会讨论这部分内容。第二种方法是使用 Template 方法。

当然,还有一个问题,如何将值转化为字符串?很幸运,Python 有办法将任意值转为字符串:将它传入 repr() 或 str() 函数。

函数 str() 用于将值转化为适于人阅读的形式,而 repr() 转化为供解释器读取的形式(如果没有等价的语法,则会发生 SyntaxError 异常)某对象没有适于人阅读的解释形式的话,str() 会返回与 repr() 等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。字符串和浮点数,有着独特的解读方式。

下面有些例子:

>>> s = 'Hello, world.'

>>> str(s)

'Hello, world.'

>>> repr(s)

"'Hello, world.'"

>>> str(1/7)

'0.14285714285714285'

>>> x = 10 * 3.25

>>> y = 200 * 200

>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'

>>> print s

The value of x is 32.5, and y is 40000...

>>> # The repr() of a string adds string quotes and backslashes:

... hello = 'hello, world\n'

>>> hellos = repr(hello)

>>> print hellos

'hello, world\n'

>>> # The argument to repr() may be any Python object:

... repr((x, y, ('spam', 'eggs')))

"(32.5, 40000, ('spam', 'eggs'))"

有两种方式可以写平方和立方表:

>>> for x in range(1, 11):

... print repr(x).rjust(2), repr(x*x).rjust(3)

... # Note use of 'end' on previous line

... print repr(x*x*x).rjust(4)

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

>>> for x in range(1, 11):

... print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

(注意第一个例子,print 在每列之间加了一个空格,它总是在参数间加入空格。)

以上是一个 str.rjust() 方法的演示,它把字符串输出到一列,并通过向左侧填充空格来使其右对齐。类似的方法还有 str.ljust() 和 str.center()。这些函数只是输出新的字符串,并不改变什么。如果输出的字符串太长,它们也不会截断它,而是原样输出,这会使你的输出格式变得混乱,不过总强过另一种选择(截断字符串),因为那样会产生错误的输出值(如果你确实需要截断它,可以使用切割操作,例如:x.ljust(n)[:n])。

还有另一个方法,str.zfill() 它用于向数值的字符串表达左侧填充 0。该函数可以正确理解正负号:

>>> '12'.zfill(5)

'00012'

>>> '-3.14'.zfill(7)

'-003.14'

>>> '3.14159265359'.zfill(5)

'3.14159265359'

方法 str.format() 的基本用法如下:

>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')

We are the knights who say "Ni!"

大括号和其中的字符会被替换成传入 str.format() 的参数。大括号中的数值指明使用传入 str.format() 方法的对象中的哪一个:

>>> print '{0} and {1}'.format('spam', 'eggs')

spam and eggs

>>> print '{1} and {0}'.format('spam', 'eggs')

eggs and spam

如果在 str.format() 调用时使用关键字参数,可以通过参数名来引用值:

>>> print 'This {food} is {adjective}.'.format(

... food='spam', adjective='absolutely horrible')

This spam is absolutely horrible.

定位和关键字参数可以组合使用:

>>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',

other='Georg')

The story of Bill, Manfred, and Georg.

'!s' (应用 str() )和 '!r' (应用 repr())可以在格式化之前转换值:

>>> import math

>>> print 'The value of PI is approximately {}.'.format(math.pi)

The value of PI is approximately 3.14159265359.

>>> print 'The value of PI is approximately {!r}.'.format(math.pi)

The value of PI is approximately 3.141592653589793.

字段名后允许可选的 ':' 和格式指令。这允许对值的格式化加以更深入的控制。下例将 Pi 转为三位精度。

>>> import math

>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))

The value of PI is approximately 3.142.

在字段后的 ':' 后面加一个整数会限定该字段的最小宽度,这在美化表格时很有用:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}

>>> for name, phone in table.items():

... print '{0:10} ==> {1:10d}'.format(name, phone)

...

Jack ==> 4098

Dcab ==> 7678

Sjoerd ==> 4127

如果你有个实在是很长的格式化字符串,不想分割它。如果你可以用命名来引用被格式化的变量而不是位置就好了。有个简单的方法,可以传入一个字典,用中括号( '[]' )访问它的键:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

>>> print 'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '

'Dcab: {0[Dcab]:d}'.format(table)

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

也可以用 ‘**’ 标志将这个字典以关键字参数的方式传入:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

>>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

这种方式与新的内置函数 vars() 组合使用非常有效。该函数返回包含所有局部变量的字典。

要进一步了解字符串格式化方法 str.format(),参见 Format String Syntax。

7.1.1. 旧式的字符串格式化

操作符 % 也可以用于字符串格式化。它以类似 sprintf()-style 的方式解析左参数,将右参数应用于此,得到格式化操作生成的字符串,例如:

>>> import math

>>> print 'The value of PI is approximately %5.3f.' % math.pi

The value of PI is approximately 3.142.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值