[Python]格式化输出(2)

本文详细介绍了Python中各种数据类型及复杂对象的格式化输出方法,包括整型、浮点型数字的格式化,字典类型输出,对象属性值输出,日期时间格式化等,并展示了如何通过参数化进行更灵活的格式控制。

Python版本:Python 2.7.13rc1

1.数字

整型

正确的写法:

>>> print 'The value of PI is approximately %d ' % (3)
The value of PI is approximately 3 
>>> print 'The value of PI is approximately {:d} '.format(3)
The value of PI is approximately 3 
>>> print 'The value of PI is approximately %d ' % (3.1415926)
The value of PI is approximately 3 

错误的写法:

>>> print 'The value of PI is approximately {:d} '.format(3.1415926)

对齐:

>>> print '%4d'%(42)
  42
>>> print '{:_>4d}'.format(42)
__42
>>> print '%04d'%(42)
0042
>>> print '{:04d}'.format(42)
0042

浮点型

>>> import math
>>> print 'The value of PI is approximately %f ' % (math.pi)
The value of PI is approximately 3.141593 
>>> print 'The value of PI is approximately {:f} '.format(math.pi)
The value of PI is approximately 3.141593

保留小数点后三位:

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

显示六个字符,其中包括小数点和小数点后三位,不足六个字符补0:

>>> print 'The value of PI is approximately %06.3f ' % (math.pi)
The value of PI is approximately 03.142 
>>> print 'The value of PI is approximately {:06.3f} '.format(math.pi)
The value of PI is approximately 03.142 

有正负号的数字

>>> print '%+d' % (42)
+42
>>> print '{:+d}'.format(42)
+42
>>> print '% d' % (-42)
-42
>>> print '{: d}'.format(-42)
-42
>>> print '% d' % (42)
 42
>>> print '{: d}'.format(42)
 42
>>> print '{:=5d}'.format((-42))
-  42

2.Dict类型的格式化输出

根据key取value:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> print '%(Sjoerd)d %(Jack)d %(Dcab)d' % table
4127 4098 7678
>>> print '{Sjoerd} {Jack} {Dcab}'.format(**table)
4127 4098 7678
>>> print '{t[Sjoerd]} {t[Jack]} {t[Dcab]}'.format(t=table)
4127 4098 7678

Dict遍历:

>>> for name, ID in table.items():
    print '{0:10} ==> {1:10d}'.format(name,ID)

Dcab       ==>       7678
Jack       ==>       4098
Sjoerd     ==>       4127
>>> for name, ID in table.items():
    print '{1:<10d} ==> {0:>10}'.format(name,ID)

7678       ==>       Dcab
4098       ==>       Jack
4127       ==>     Sjoerd

List 取值:

>>> table2 = ["Sjoerd","Jack","Dcab"]
>>> print '{t[0]} {t[2]}'.format(t=table2)
Sjoerd Dcab

3.输出对象的属性值

>>> class Plant(object):
    type = 'tree'
    kinds = [{'name':'oak'},{'name':'maple'}]


>>> print '{p.type}: {p.kinds[0][name]}'.format(p=Plant())
tree: oak

4.Datetime

>>> from datetime import datetime
>>> dt = datetime(2001, 2, 3, 4, 5)
>>> print '{:%Y-%m-%d %H:%M}'.format(dt)
2001-02-03 04:05
>>> print '{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
2001-02-03 04:05

5.参数化的格式

设置参数精度:

>>> print '%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)
Gib = 2.718
>>> print '{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
Gib = 2.718

参数位置:

>>> print '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
     +2.72

6.重写format类

>>> class HAL9000(object):

    def __format__(self, format):
        if (format == 'open-the-pod-bay-doors'):
            return "I'm afraid I can't do that."
        return 'HAL 9000'

>>> print '{:open-the-pod-bay-doors}'.format(HAL9000())
I'm afraid I can't do that.

### Python格式化输出的方法 Python 提供了多种方式进行格式化输出,主要包括 `%` 运算符、`str.format()` 方法以及 f-string(从 Python 3.6 开始支持)。以下是每种方法的具体介绍及其示例。 #### 1. 使用 `%` 运算符进行格式化 这是较早的一种格式化方式,类似于 C 风格的 `printf` 函数。它使用占位符来指定数据类型并插入相应的值。 ```python name = "Alice" age = 25 message = "名字是:%s,年龄是:%d" % (name, age) print(message) # 输出: 名字是:Alice,年龄是:25 ``` 这种形式简单直观,但在复杂场景下不够灵活[^1]。 #### 2. 使用 `str.format()` 方法 `str.format()` 是一种更现代的方式,允许通过位置索引或命名字段来进行格式化操作。 ##### 基本用法 ```python age = 2 s = '已经上' message = "乔治说: 我今年{}岁了,{}幼儿园!".format(age, s) print(message) # 输出: 乔治说: 我今年2岁了,已经上幼儿园! ``` ##### 定义参数对象的输出格式 可以在 `{}` 大括号内定义具体的格式说明符,例如浮点数的小数位数。 ```python formatted_float = "{:.2f}".format(1) print(formatted_float) # 输出: 1.00 mixed_formatting = "{1:.2f} {0:.1f}".format(1, 2) print(mixed_formatting) # 输出: 2.00 1.0 ``` ##### 命名字段 可以通过关键字参数实现更具可读性的格式化。 ```python named_format = "{num:.2f}".format(num=1) print(named_format) # 输出: 1.00 ``` 这种方式相较于 `%` 更加清晰易懂,并且提供了更多的灵活性[^3]。 #### 3. 使用 f-string(仅限 Python 3.6 及以上版本) f-string 是一种简洁高效的字符串插值方式,在表达式前加上字母 `f` 或者 `F` 即可嵌入变量或其他表达式的值。 ```python name = "Bob" age = 30 greeting = f"你好,{name}! 你今年{age}岁了。" print(greeting) # 输出: 你好,Bob! 你今年30岁了。 ``` 对于数值类型的格式控制同样适用: ```python value = 3.14159 formatted_value = f"{value:.2f}" print(formatted_value) # 输出: 3.14 ``` 此方法不仅性能优越而且语法优雅,推荐在新项目中优先采用[^5]。 --- ### 总结 三种主要的 Python 格式化输出手段各有优劣: - **%运算符**适合简单的场合; - **str.format()**提供更强的功能性和扩展能力; - **f-string**则以其高效与直观成为首选方案之一。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值