Python字串的格式化的詳細介紹

不言
發布: 2019-03-26 11:15:07
轉載
2107 人瀏覽過

這篇文章帶給大家的內容是關於Python字串的格式化的詳細介紹,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

相信很多人在格式化字串的時候都用"%s" % v的語法,PEP 3101 提出一種更先進的格式化方法str.format() 並成為Python 3 的標準用來替換舊的%s 格式化語法,CPython 從2.6 開始已經實現了這一方法(其它解釋器未考證)。

format()

新的format() 方法其實比較像是簡略版的範本引起(Template Engine),功能非常豐富。

模板中替換變數以 {} 包圍,且由 : 分為兩部分,其中後半部 format_spec 在後面會單獨討論。

前半部有三種用法:

  • 空白
  • 代表位置的數字
  • 代表keyword的識別碼

#這與函數呼叫的參數類別是一致的

print("{} {}".format("Hello", "World"))
# 等同于以下几种
print("{0} {1}".format("Hello", "World"))
print("{hello} {world}".format(hello="Hello", world="World"))
print("{0}{1}{0}".format("H", "e"))

# Hello World
# Hello World
# Hello World
# HeH
登入後複製

除此之外,就像函數參數的解包一樣,format() 中也可以直接使用解包運算

print("{author}.{city}".format(**{"author": "Miracle", "city": "上海"}))
print("{} {}".format(*["Miracle", "上海"]))

Miracle.上海
Miracle 上海
登入後複製

在模板中也可以透​​過.identifier 和[key] 的方式取得變數內的屬性或值(需要注意的是"{}{}" 相當於"{0}{1}")

data = {'author': 'Miracle', 'like': 'papapa'}
print("Author: {0[author]}, Like: {0[like]}".format(data))
langs = ["Python", "Ruby"]
print("{0[0]} vs {0[1]}".format(langs))

print("\n====\nHelp(format):{.__doc__}".format(str.format))

# Name: Python, Score: 100
# Python vs Ruby

# ====
# Help(format):
#  S.format(*args, **kwargs) -> str
登入後複製

強制轉換,可以透過! r|s|a 的方式對替換的變數進行強制轉換

  • "{!r}" 對變數呼叫repr()
  • "{ !s}" 對變數呼叫str()
  • "{!a}" 對變數呼叫ascii()

#冒號之後的部分定義輸出的樣式

align 代表對齊方向,通常要配合width 使用,而fill 則是填充的字元(預設為空白):

for align, text in zip("<^>", ["left", "center", "right"]):
   # 务必看懂这句话
   print("{:{fill}{align}16}".format(text, fill=align, align=align))

print("{:0=10}".format(100)) # = 只允许数字

# left<<<<<<<<<<<<
# ^^^^^center^^^^^
# >>>>>>>>>>>right
# 0000000100
登入後複製

同時可以看出,樣式設定裡面可以嵌套{} ,但是必須透過keyword指定,且只能嵌套一層。

接下來是符號樣式: |-|' ' 分別指定數字是否需要強制符號(其中空格是指在正數的時候不顯示但保留一位空格)

print("{0:+}\n{1:-}\n{0: }".format(3.14, -3.14))

# +3.14
# -3.14
# 3.14
登入後複製

用於表示特殊格式的數字(二進位、十六進位等)是否需要前綴符號

逗號也是用來表示數字時是否需要在千位處進行分隔

#0 相當於前面的{:0=} 右對齊並用0 補充空位

print("Binary: {0:b} => {0:#b}".format(3))
print("Large Number: {0:} => {0:,}".format(1.25e6))
print("Padding: {0:16} => {0:016}".format(3))

# Binary: 11 => 0b11
# Large Number: 1250000.0 => 1,250,000.0
# Padding:                3 => 0000000000000003
登入後複製

最後小胖給大家介紹一下熟悉的小數點精度問題, .n 和格式化類型。

這裡只給一些範例,詳細內容可以查閱文件:

from math import pi
print("pi = {pi:.2}, also = {pi:.7}".format(pi=pi))

# pi = 3.1, also = 3.141593
登入後複製

Integer

for t in "b c d #o #x #X n".split():
   print("Type {0:>2} of {1} shows: {1:{t}}".format(t, 97, t=t))

# Type  b of 97 shows: 1100001
# Type  c of 97 shows: a
# Type  d of 97 shows: 97
# Type #o of 97 shows: 0o141
# Type #x of 97 shows: 0x61
# Type #X of 97 shows: 0X61
# Type  n of 97 shows: 97
登入後複製

Float

for t, n in zip("eEfFgGn%", [12345, 12345, 1.3, 1.3, 1, 2, 3.14, 0.985]):
   print("Type {} shows: {:.2{t}}".format(t, n, t=t))

# Type e shows: 1.23e+04
# Type E shows: 1.23E+04
# Type f shows: 1.30
# Type F shows: 1.30
# Type g shows: 1
# Type G shows: 2
# Type n shows: 3.1
# Type % shows: 98.50%
登入後複製

String (default)

try:
   print("{:s}".format(123))
except:
   print("{}".format(456))

# 456
登入後複製

這篇文章到這裡就已經全部結束了,更多其他精彩內容可以關注PHP中文網的python影片教學專欄!

#

以上是Python字串的格式化的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!