日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

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

常見的占位符

占位符

替換內容

%d

整數

%f

浮點數

%s

字符串,可以把任何數據類型轉換為字符串

%x

十六進制整數

%?

有幾個占位符

其中,格式化整數和浮點數還可以指定是否補0和整數與小數的位數:

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()方法,它會用傳入的參數依次替換字符串內的占位符{0}、{1}......

基本用法

不帶編號,即{}

帶數字編號,可調換順序,即{1}、{2}

帶關鍵字,即{a}、{tom}

# 不帶字段

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

進階用法

<(默認)左對齊、>右對齊、^中間對齊、=(只用于數字)在小數點后進行補齊。

取位數{: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位小數

print('{} is {:.2f}'.format(1.123,1.123))

1.123 is 1.12

# 取2位小數,右對齊,取10位

print('{0} is {0:>10.2f}'.format(1.123))

1.123 is 1.12

總結

以上是生活随笔為你收集整理的python右对齐格式化输出_python笔记-格式化输出(%和format的用法)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。