日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

python右对齐格式化输出_python笔记-格式化输出(%和format的用法)

發(fā)布時(shí)間:2025/3/20 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python右对齐格式化输出_python笔记-格式化输出(%和format的用法) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

常見的占位符

占位符

替換內(nèi)容

%d

整數(shù)

%f

浮點(diǎn)數(shù)

%s

字符串,可以把任何數(shù)據(jù)類型轉(zhuǎn)換為字符串

%x

十六進(jìn)制整數(shù)

%?

有幾個(gè)占位符

其中,格式化整數(shù)和浮點(diǎn)數(shù)還可以指定是否補(bǔ)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

進(jìn)階用法

<(默認(rèn))左對齊、>右對齊、^中間對齊、=(只用于數(shù)字)在小數(shù)點(diǎn)后進(jìn)行補(bǔ)齊。

取位數(shù){:4s}、{:.2f}等。

# 默認(rèn)左對齊

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。