python format格式化字串

2021-06-21 00:39:36 字數 996 閱讀 8923

你可以用字串的format方法來格式化輸出字串。 比如;

>>>

print

'we are the who say "!"'

.format(

'knights'

,'ni') we

arethe

knights

whosay

"ni!"

括號內的字元(稱為格式字段)被替換的物件。{}括號中的數字是指替換的位置,裡面的數字,比如0,1表示替換元組的索引位置。

>>>

print

' and '

.format(

'spam'

,'eggs')

spam

andeggs

>>>

print

' and '

.format(

'spam'

,'eggs')

eggs

andspam

如果使用關鍵字引數的格式方法,其值被稱為使用的引數名稱。

>>>

print

'this is .'

.format(

...food

='spam'

,adjective

='absolutely horrible')

this

spam

isabsolutely

horrible.

下面是位置和關鍵字引數的任意組合:

>>>

print

'the story of , , and .'

.format(

'bill'

,'manfred'

,...

other

='georg')

thestory

ofbill

,manfred

,and

georg

.

Python format 格式化函式

數字 格式輸出 描述3.1415926 3.14 保留小數點後兩位 3.1415926 3.14 帶符號保留小數點後兩位 1 1.00 帶符號保留小數點後兩位 2.71828 3不帶小數505 數字補零 填充左邊,寬度為2 55 數字補x 填充右邊,寬度為4 1010xx 數字補x 填充右邊,寬度為...

Python format 格式化函式

python2.6 開始,新增了一種格式化字串的函式 str.format 它增強了字串格式化的功能。基本語法是通過 和 來代替以前的 format 函式可以接受不限個引數,位置可以不按順序。不設定指定位置,按預設順序 print format hello world 設定指定位置 print fo...

Python format 格式化函式

python2.6 開始,新增了一種格式化字串的函式 str.format 它增強了字串格式化的功能。栗子 name 雷歐 age 28 add m78星雲 print 你好,我叫 我來自 今年 歲.format name,add,age print 你好,我叫 name 我來自 add 今年 ag...