[python] format()

在输出时,如果有多个参数的输出需求,有以下两种输出方法:

1. print(变量名 + "一句话或者符号" + 变量名)  不推荐的方法

注意:这里的变量需要是str类型

2. print('{0}blabla...{1}blabla....'.format(变量1, 变量2)) 推荐

举个例子:

name = 'Jean'
age = 17

print('{0} is a student and she is {1} years old.'.format(name, age))
print(name + ' is a student and she is ' + str(age) + ' years old.')

format 方法所做的事情便是将每个参数值替换至格式所在的位置,可以格式化输出:

# 对于浮点数 '0.333' 保留小数点(.)后三位
print('{0:.3f}, {1}, {2:.3f}, {3}, {4}'.format(1.0/3, 1.0/3, 1/3, 1/3, type(1/3)))
# 使用下划线填充文本,并保持文字处于中间位置
# 使用 (^) 定义字符串长度
print('{0:_^11}'.format('hello'))
# 基于关键词输出 'Goodgirl wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Goodgirl', book='A Byte of Python'))

输出:

0.333, 0.3333333333333333, 0.333, 0.3333333333333333, <class 'float'>
___hello___
Goodgirl wrote A Byte of Python

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值