1. 程式人生 > >python——格式化輸出、占位符、format()

python——格式化輸出、占位符、format()

nbsp int 十進制 border 默認 %s code order pri

占位符

常用占位符 描述
%s 字符串
%d 十進制整數
%o 八進制
%x 十六進制
%f 浮點數

>>> print(%s % hello world)  # 字符串輸出
hello world
>>> print(%20s % hello world)  # 右對齊,取20位,不夠則補位
         hello world
>>> print(%-20s % hello world)  # 左對齊,取20位,不夠則補位
hello world         
>>> print(%.2s % hello world) # 取2位 he >>> print(%10.2s % hello world) # 右對齊,取2位 he >>> print(%-10.2s % hello world) # 左對齊,取2位 he >>> print(%d元 % 10) 10元 >>> print(%f % 1.11) # 默認保留6位小數 1.110000 >>> print(%.1f % 1.11) # 取1位小數
1.1

format()

相對基本格式化輸出采用‘%’的方法,format()功能更強大。

>>> print({} {}.format(hello,world))  # 不帶字段
hello world
>>> print({0} {1}.format(hello,world))  # 帶標號
hello world
>>> print({0} {1} {0}.format(hello,world))  # 打亂順序
hello world hello
>>> print({1} {1} {0}
.format(hello,world)) world world hello >>> print({a} {tom} {a}.format(tom=hello,a=world)) # 帶關鍵字 world hello world

python——格式化輸出、占位符、format()