Python-格式化與格式

1. %?格式化

親愛的×××你好,您的月租費(fèi)用為××,余額為××

××的內(nèi)容根據(jù)變量變化,因此需要一種簡便的格式化字符串的方式。

 >>>'hello, %s' %  'world'
 'hello, world'
 >>>'hi, %s, you have %d.' % ('Thiago', 10000000)
 'hi, Thiago, you have 10000000.'

%運(yùn)算符是用來格式化字符串的。
在字符內(nèi)部,
%s表示用字符串(string)替換,
%d表示用整數(shù)(digit?)替換,
%f表示用浮點(diǎn)數(shù)(float)替換,
%x表示用十六進(jìn)制整數(shù)(hex)替換。

有幾個(gè)%?占位符,后面就跟幾個(gè)變量,或者值;順序要對(duì)應(yīng)好,用括號(hào)括起來;如果只有一個(gè)%?,括號(hào)可以省略。
如果不確定應(yīng)該用什么,那么%s永遠(yuǎn)起作用。
字符串里面如果有%字符,應(yīng)該加一個(gè)%來轉(zhuǎn)義,既%%,這樣才能吧百分號(hào)print出來。

2. .format格式化

 age = 20
 name = 'Thiago'
 print('{0} was {1} years old when he started learning Python.' .format(name, age))
 print('Why is {0} playing with a python?' .format(name))

輸出為:

 Thiago was 20 years old when he started learning Python.
 Why is Thiago playing with a python?

數(shù)字只是可選項(xiàng),你也可以寫成:

 print('{} was {} years old when he started learning Python' .format(name, age))
 print('Why is {} playing with a python?' .format(name))

Python中.format的作用就是將每個(gè)參數(shù)替換致格式所在的位置。這之中可以有更詳細(xì)的格式:

 #對(duì)于浮點(diǎn)數(shù)‘0.333’保留小數(shù)點(diǎn)后三位:
 print('{0:.3f}' .format(1.0/3))
 #基于關(guān)鍵詞輸出‘Thiago is reading A Bite of Pyhton'
 print('{name} is reading {book}' .format(name='Thiago', book='A Bite of Python'))

輸出為:

 0.333
 Thiago is reading A Bite of Python

3.print總是會(huì)以\n (新一行)結(jié)尾

因此重復(fù)調(diào)用print會(huì)在相互獨(dú)立的兩行中打?。粸榱吮苊膺@一方式的換行,可以通過 end 指定其應(yīng)該以‘空白’結(jié)尾:

 print('a', end= '')  
 print('b', end= '')

輸出結(jié)果為:

 ab

或者你可以指定end以‘空格’結(jié)尾:

 print('a', end= ' ')
 print('b', end= ' ')
 print('c')

輸出結(jié)果為:

 a b c

4.字符串中的反斜杠(backslash\)

在一個(gè)字符串中,一個(gè)放置在某句結(jié)尾的\表示字符串將在下一行繼續(xù),但是并沒有生成新的一行:

 ''this is the first line,\
    but this is still the first line.''

相當(dāng)于:

 ''this is the first line, but this is still the first line.''

反斜杠的作用:

物理行(physical line)是在編程時(shí)你所看到的內(nèi)容,邏輯行(logical line)是Python 所看到的單個(gè)語句。 Python會(huì)假定每個(gè)物理行對(duì)應(yīng)一個(gè)邏輯行。

如果你有一個(gè)非常長的語句,那么可以使用反斜杠將其拆分成多個(gè)物理行(但是他們?nèi)稳皇且粋€(gè)邏輯行),這被稱作顯式行鏈接(explicit line joining):

 s='this is a string.\
 and this continues that string.'
 print(s)

輸出為:

 this is a string. and this continues that string.

5.縮進(jìn)

放置在一起的語句必須要有相同的縮進(jìn)。每一組這樣的語句被成為一個(gè)塊,block

官方建議使用4個(gè)空格來縮進(jìn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容