python中的格式化輸出用法總結,python用法

來源:互聯網
上載者:User

python中的格式化輸出用法總結,python用法

本文執行個體總結了python中的格式化輸出用法。分享給大家供大家參考,具體如下:

Python一共有兩種格式化輸出文法。

一種是類似於C語言printf的方式,稱為 Formatting Expression

>>> '%s %d-%d' % ('hello', 7, 1)'hello 7-1'

另一種是類似於C#的方式,稱為String Formatting Method Calls

>>> '{0} {1}:{2}'.format('hello', '1', '7')'hello 1:7'

第一種方式可以指定浮點數的精度,例如

>>> '%.3f' % 1.234567869'1.235'

運行時動態指定浮點數的精度

但是當代碼在運行中如何動態地通過參數來指定浮點數的精度呢?

python的神奇之處在於它又提供了一種非常方便的文法。只需要在 typecode(這裡是f)之前加一個 *,浮點數的精度就用它前面的數字來指定。

>>> for i in range(5):... '%.*f' % (i, 1.234234234234234)...'1''1.2''1.23''1.234''1.2342'

通過輸出結果可以看出,精度都是在運行時動態指定,這樣就省去了格式化字串的拼湊。

使用 String Formatting Method Calls 可以更簡潔地完成功能。

>>> for i in range(5):...  '{0:.{1}f}'.format(1 / 3.0, i)...'0''0.3''0.33''0.333''0.3333'

實現一個簡單的模板工具

Django提供的範本語言,可以讓我們通過一個dict(字典)把python變數綁定的html檔案中,其實利用python的格式化輸出我們也可以僅僅做一個文本替換功能。

>>> replay = """... Hello World Cup...... Germany vs Brazil... %(germany)d : %(brazil)d""">>> print(replay % {'germany': 7, 'brazil': 1})Hello World Cup...Germany vs Brazil7 : 1

還可以這樣玩

>>> germany = 7>>> brazil = 1>>> '%(germany)d : %(brazil)d' % vars()'7 : 1'

在格式化字串中訪問對象屬性和字典索引值

>>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'pc'})'My pc runs linux'>>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'pc'})'My pc runs linux'

在格式化字串中通過下標(正整數)訪問list元素

>>> somelist = list('SPAM')>>> 'first={0[0]}, third={0[2]}'.format(somelist)'first=S, third=A'>>> 'first={0}, last={1}'.format(somelist[1], somelist[-1])'first=P, last=M'>>> parts = somelist[0], somelist[-1], somelist[1:-1]>>> 'first={0}, last={1}, middle={2}'.format(*parts)"first=S, last=M, middle=['P', 'A']">>>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.