python右对齐格式化输出_python笔记-格式化输出(%和format的用法)
常見的占位符
占位符
替換內(nèi)容
%d
整數(shù)
%f
浮點數(shù)
%s
字符串,可以把任何數(shù)據(jù)類型轉(zhuǎn)換為字符串
%x
十六進制整數(shù)
%?
有幾個占位符
其中,格式化整數(shù)和浮點數(shù)還可以指定是否補0和整數(shù)與小數(shù)的位數(shù):
print('Hi, %s, you have $%d.' % ('Michael', 1000000))
Hi, Michael, you have $1000000.
print('%d-%02d' % (3, 1))
3-01
print('%.2f' % 3.1415926)
3.14
format()
另一種格式化字符串的方法是使用字符串的format()方法,它會用傳入的參數(shù)依次替換字符串內(nèi)的占位符{0}、{1}......
基本用法
不帶編號,即{}
帶數(shù)字編號,可調(diào)換順序,即{1}、{2}
帶關(guān)鍵字,即{a}、{tom}
# 不帶字段
print('{} {}'.format('hello', 'world'))
hello world
# 帶數(shù)字編號
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
# 帶關(guān)鍵字
print('{a} {tom} {a}'.format(tom='hello', a='world'))
world hello world
進階用法
<(默認)左對齊、>右對齊、^中間對齊、=(只用于數(shù)字)在小數(shù)點后進行補齊。
取位數(shù){:4s}、{:.2f}等。
# 默認左對齊
print('{} and {}'.format('hello', 'world'))
hello and world
# 取10位左對齊,取10位右對齊
print('{:10s} and {:>10s}'.format('hello', 'world'))
hello and world
# 取10位中間對齊
print('{:^10s} and {:^10s}'.format('hello', 'world'))
hello and world
# 取2位小數(shù)
print('{} is {:.2f}'.format(1.123,1.123))
1.123 is 1.12
# 取2位小數(shù),右對齊,取10位
print('{0} is {0:>10.2f}'.format(1.123))
1.123 is 1.12
總結(jié)
以上是生活随笔為你收集整理的python右对齐格式化输出_python笔记-格式化输出(%和format的用法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 十三种技术文档模板_竞品分析|关于产品规
- 下一篇: 眼图在通信系统中有什么意义_解读CRM系