python string format

截取自官方文檔
體會一下各種format方式的強大!

Accessing arguments by position:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'
Accessing arguments by name:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
Accessing arguments’ attributes:
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...  def __init__(self, x, y):
...      self.x, self.y = x, y
...  def __str__(self):
...      return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
Accessing arguments’ items:
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
Replacing %s and %r:
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
Aligning the text and specifying a width:
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
Replacing %+f, %-f, and % f and specifying a sign:
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
Replacing %x and %o and converting the value to different bases:
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
Using the comma as a thousands separator:
>>> '{:,}'.format(1234567890)
'1,234,567,890'
Expressing a percentage:
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'
Using type-specific formatting:
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
Nesting arguments and more complex examples:
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...  '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12): 
...          for base in 'dXob':
...              print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
...          print()
... 
5 5 5 101 
6 6 6 110 
7 7 7 111 
8 8 10 1000 
9 9 11 1001 
10 A 12 1010 
11 B 13 1011
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蚀乔,一起剝皮案震驚了整個濱河市求妹,隨后出現(xiàn)的幾起案子月褥,更是在濱河造成了極大的恐慌昂利,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鸵隧,死亡現(xiàn)場離奇詭異张弛,居然都是意外死亡荒典,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門吞鸭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來寺董,“玉大人,你說我怎么就攤上這事刻剥≌诳В” “怎么了?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵造虏,是天一觀的道長御吞。 經(jīng)常有香客問我麦箍,道長,這世上最難降的妖魔是什么陶珠? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任挟裂,我火速辦了婚禮,結(jié)果婚禮上背率,老公的妹妹穿的比我還像新娘话瞧。我一直安慰自己嫩与,他們只是感情好寝姿,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著划滋,像睡著了一般饵筑。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上处坪,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天根资,我揣著相機與錄音,去河邊找鬼同窘。 笑死玄帕,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的想邦。 我是一名探鬼主播裤纹,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼丧没!你這毒婦竟也來了鹰椒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤呕童,失蹤者是張志新(化名)和其女友劉穎漆际,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體夺饲,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡奸汇,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了往声。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片擂找。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖烁挟,靈堂內(nèi)的尸體忽然破棺而出婴洼,到底是詐尸還是另有隱情,我是刑警寧澤撼嗓,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布柬采,位于F島的核電站欢唾,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏粉捻。R本人自食惡果不足惜礁遣,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望肩刃。 院中可真熱鬧祟霍,春花似錦、人聲如沸盈包。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽呢燥。三九已至崭添,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間叛氨,已是汗流浹背呼渣。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留寞埠,地道東北人屁置。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像仁连,于是被迫代替她去往敵國和親蓝角。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容

  • 第一次籌劃準備執(zhí)行這樣的一場活動怖糊,過程簡單但是瑣事煩碎帅容,整場下來雖然沒有出現(xiàn)什么特殊狀況,起碼在保證大家人身安全的...
    是京京呀閱讀 1,035評論 0 2
  • 拋開那些讓人頭大的理論伍伤,我來談談以結(jié)果為導向的過程管理 雨點向茉莉花微語道:“把我永久地留在你的心里吧并徘。”茉莉花嘆...
    快樂的五顆星閱讀 1,552評論 0 1