python数字转字符串格式化_用Python将数字格式化为字符串

从Python2.6开始,有一个替代方法:方法str.format()。下面是一些使用现有字符串格式运算符(%)的示例:>>> "Name: %s, age: %d" % ('John', 35)

'Name: John, age: 35'

>>> i = 45

>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)

'dec: 45/oct: 055/hex: 0X2D'

>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)

'MM/DD/YY = 12/07/41'

>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)

'Total with tax: $14.07'

>>> d = {'web': 'user', 'page': 42}

>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d

'http://xxx.yyy.zzz/user/42.html'

以下是等效的代码片段,但使用str.format():>>> "Name: {0}, age: {1}".format('John', 35)

'Name: John, age: 35'

>>> i = 45

>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)

'dec: 45/oct: 0o55/hex: 0X2D'

>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41)

'MM/DD/YY = 12/07/41'

>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825)

'Total with tax: $14.07'

>>> d = {'web': 'user', 'page': 42}

>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)

'http://xxx.yyy.zzz/user/42.html'

与Python2.6+一样,所有Python3发行版(到目前为止)都了解如何同时执行这两种操作。我不知羞耻地把这些东西直接从my hardcore Python intro book和介绍+中间Python courses I offer的幻灯片中撕了出来。:-)

2018年8月更新:当然,现在我们有了the f-string feature in 3.6,我们需要的等价示例,即,是的,另一种选择:>>> name, age = 'John', 35

>>> f'Name: {name}, age: {age}'

'Name: John, age: 35'

>>> i = 45

>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'

'dec: 45/oct: 0o55/hex: 0X2D'

>>> m, d, y = 12, 7, 41

>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"

'MM/DD/YY = 12/07/41'

>>> f'Total with tax: ${13.00 * 1.0825:.2f}'

'Total with tax: $14.07'

>>> d = {'web': 'user', 'page': 42}

>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"

'http://xxx.yyy.zzz/user/42.html'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值