1. %?格式化
親愛(ài)的×××你好削茁,您的月租費(fèi)用為××蒙谓,余額為××
××的內(nèi)容根據(jù)變量變化柜候,因此需要一種簡(jiǎn)便的格式化字符串的方式。
>>>'hello, %s' % 'world' 'hello, world' >>>'hi, %s, you have %d.' % ('Thiago', 10000000) 'hi, Thiago, you have 10000000.'
%運(yùn)算符是用來(lái)格式化字符串的汽摹。
在字符內(nèi)部,
%s表示用字符串(string)替換苦锨,
%d表示用整數(shù)(digit逼泣?)替換,
%f表示用浮點(diǎn)數(shù)(float)替換舟舒,
%x表示用十六進(jìn)制整數(shù)(hex)替換拉庶。
有幾個(gè)%?占位符,后面就跟幾個(gè)變量秃励,或者值氏仗;順序要對(duì)應(yīng)好,用括號(hào)括起來(lái)夺鲜;如果只有一個(gè)%?皆尔,括號(hào)可以省略。
如果不確定應(yīng)該用什么币励,那么%s永遠(yuǎn)起作用慷蠕。
字符串里面如果有%字符,應(yīng)該加一個(gè)%來(lái)轉(zhuǎn)義食呻,既%%流炕,這樣才能吧百分號(hào)print出來(lái)。
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)搁进,你也可以寫(xiě)成:
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ú)立的兩行中打印饼问;為了避免這一方式的換行影兽,可以通過(guò) 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ù)莱革,但是并沒(méi)有生成新的一行:
''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è)語(yǔ)句。 Python會(huì)假定每個(gè)物理行對(duì)應(yīng)一個(gè)邏輯行盅视。
如果你有一個(gè)非常長(zhǎng)的語(yǔ)句捐名,那么可以使用反斜杠將其拆分成多個(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)
放置在一起的語(yǔ)句必須要有相同的縮進(jìn)闹击。每一組這樣的語(yǔ)句被成為一個(gè)塊,block
官方建議使用4個(gè)空格來(lái)縮進(jìn)