[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,
___hello___
Goodgirl wrote A Byte of Python

你可能感兴趣的:(python)