目录

Python之format函数对齐设置格式化字符串和数字输出

目录

Python之format函数对齐设置、格式化字符串和数字输出

format函数格式化字符串输出、设置数字格式、对齐设置

直接看代码,一目了然。

1.格式化字符串

#按默认顺序获取format中的数据
print('编程语言{}获得{}学分。'.format('python', 100))
编程语言python获得100学分
#按指定顺序获取format中的数据
print('编程语言{0}获得{1}学分。'.format('python', 100))
编程语言python获得100学分
#使用关键字索引
print('编程语言{name}获得{score}学分。'.format(name='python', score=100))
编程语言python获得100学分

2.设置数字格式

print('{:.2f}'.format(3.1415926))  
3.14
print('{:.2%}'.format(3.1415926))  
314.16%
  表示要设置的值
.2  表示保留小数点后两位
f   表示返回浮点数也就是小数
%   表示设置成百分比格式

3.对齐设置

#左对齐,不足部分默认用空格填充
print('|{:<10}|'.format('python'))
|python    |
#左对齐,不足部分用□填充
print('|{:□<10}|'.format('python'))
|python□□□□|

<    表示左对齐
>    表示右对齐
^    表示居中对齐
10   表示花括号中的字符串长度为10
   表示如果字符串不足“□”填充也可以用其他字符