码迷,mamicode.com
首页 > 编程语言 > 详细

python 中 打印及格式化字符串的相关方法

时间:2017-10-02 23:04:58      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:...   cli   abap   打印   数字   cte   适合   div   阶段   

原文

将值转换为字符串

Python 有多种方式将任何值转为字符串: 将它传给 repr() 或 str() 函数.

repr() 和 str() 的区别,看几个例子:

>>> print(str(‘123‘))       
123                         
>>> print(str(123))         
123                         
>>> print(repr(‘123‘))      
‘123‘                       
>>> print(repr(123))        
123

 

技术分享技术分享

再看这个例子

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(str(now))
2017-04-22 15:41:33.012917
>>> print(repr(now))
datetime.datetime(2017, 4, 22, 15, 41, 33, 12917)

 

技术分享技术分享

因此 str() 与 repr() 的不同在于:

  • str() 的输出追求可读性,输出格式要便于理解,适合用于输出内容到用户终端。
  • repr() 的输出追求明确性,除了对象内容,还需要展示出对象的数据类型信息,适合开发和调试阶段使用。

 

str.format 的使用

括号及其里面的字符 (称作 format field) 将会被 format() 中的参数替换. 在括号中的数字用于指向传入对象在 format() 中的位置.

>>> print(‘{0} and {1}‘.format(‘spam‘, ‘eggs‘))
spam and eggs
>>> print(‘{1} and {0}‘.format(‘spam‘, ‘eggs‘))
eggs and spam
技术分享技术分享

如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数.

>>> print(‘This {food} is {adjective}.‘.format(
...       food=‘spam‘, adjective=‘absolutely horrible‘))
This spam is absolutely horrible.
技术分享技术分享

可选项 ‘:‘ 和格式标识符可以跟着 field name. 这就允许对值进行更好的格式化. 下面的例子将 Pi 保留到小数点后三位.

>>> import math
>>> print(‘The value of PI is approximately {0:.3f}.‘.format(math.pi))
The value of PI is approximately 3.142.
技术分享技术分享

‘!a‘ (使用 ascii()), ‘!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.
技术分享技术分享

格式化字典,使用 **

>>> 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
技术分享技术分享

 

旧式字符串格式化

使用 %进行字符串格式化

>>> import math
>>> print(‘The value of PI is approximately %5.3f.‘ % math.pi)
The value of PI is approximately 3.142.
技术分享技术分享

 

python 中 打印及格式化字符串的相关方法

标签:...   cli   abap   打印   数字   cte   适合   div   阶段   

原文地址:http://www.cnblogs.com/lemos/p/7622763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!