python语言格式化_Python 内置格式化语言简介

>>> class Point(object):

def __init__(self, x, y):

self.x, self.y = x, y

def __str__(self):

return 'Point({self.x}, {self.y})'.format(self=self)

>>> str(Point(4, 2))

'Point(4, 2)'

左对齐< 右对齐 > 中间对齐 ^ 对齐填充 *[<>^]

>>> '{:<30}'.format('left aligned')

'left aligned '

>>> '{:>30}'.format('right aligned')

' right aligned'

>>> '{:^30}'.format('centered')

' centered '

>>> '{:*^30}'.format('centered') #使用*作为填充字符

'***********centered***********'

带符号浮点数

>>> '{:+f}; {:+f}'.format(3.14, -3.14) # 始终显示符号

'+3.140000; -3.140000'

>>> '{: f}; {: f}'.format(3.14, -3.14) # 在正数前显示空格

' 3.140000; -3.140000'

>>> '{:-f}; {:-f}'.format(3.14, -3.14) # 只显示负数符号,相当于 '{:f}; {:f}'

'3.140000; -3.140000'

二进制格式化

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)

'int: 42; hex: 2a; oct: 52; bin: 101010'

>>> # 显示 0x, 0o, or 0b 作为进制符号

>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)

'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'

千分符格式化

>>> '{:,}'.format(1234567890)

'1,234,567,890'

日期格式化

>>> import datetime

>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)

>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)

'2010-07-04 12:15:58'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值