国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中字符串格式化str.format的詳細介紹

2019-11-25 16:21:04
字體:
來源:轉載
供稿:網友

前言

Python 在 2.6 版本中新加了一個字符串格式化方法: str.format() 。它的基本語法是通過 {} 和 : 來代替以前的 %.。

格式化時的占位符語法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”規則

通過位置

str.format() 可以接受不限個參數,位置可以不按順序:

>>> "{0} {1}".format("hello", "world")'hello world'>>> "{} {}".format("hello", "world")'hello world'>>> "{1} {0} {1}".format("hello", "world")'world hello world'

通過關鍵字參數

使用關鍵參數時字符串中需要提供參數名:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)'I am huoty, age is 18'>>> user = {"name": "huoty", "age": 18}>>> "I am {name}, age is {age}".format(**user)'I am huoty, age is 18'

通過對象屬性

str.format() 可以直接讀取用戶屬性:

>>> class User(object):...  def __init__(self, name, age):...   self.name = name...   self.age = age...   ...  def __str__(self):...   return "{self.name}({self.age})".format(self=self)...  ...  def __repr__(self):...   return self.__str__()...  ...>>> user = User("huoty", 18)>>> userhuoty(18)>>> "I am {user.name}, age is {user.age}".format(user=user)'I am huoty, age is 18'

通過下標

在需要格式化的字符串內部可以通過下標來訪問元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]>>> "I am {0[0]}, age is {1[2]}".format(names, ages)'I am huoty, age is 8'>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定轉化

可以指定字符串的轉化類型:

 conversion ::= "r" | "s" | "a"

其中 "!r" 對應 repr(); "!s" 對應 str(); "!a" 對應 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充與對齊

填充常跟對齊一起使用。^, <, > 分別是居中、左對齊、右對齊,后面帶寬度, : 號后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。

>>> "{:>8}".format("181716")' 181716'>>> "{:0>8}".format("181716")'00181716'>>> "{:->8}".format("181716")'--181716'>>> "{:-<8}".format("181716")'181716--'>>> "{:-^8}".format("181716")'-181716-'>>> "{:-<25}>".format("Here ")'Here -------------------->'

浮點精度

用 f 表示浮點類型,并可以在其前邊加上精度控制:

>>> "[ {:.2f} ]".format(321.33345)'[ 321.33 ]'>>> "[ {:.1f} ]".format(321.33345)'[ 321.3 ]'>>> "[ {:.4f} ]".format(321.33345)'[ 321.3335 ]'>>> "[ {:.4f} ]".format(321)'[ 321.0000 ]'

還可以為浮點數指定符號,+ 表示在正數前顯示 +,負數前顯示 -; (空格)表示在正數前加空格,在幅負數前加 -;- 與什么都不加({:f})時一致:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)'+3.141593; -3.141593'>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)' 3.141593; -3.141593'>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)'3.141593; -3.141593'>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)'3.141593; -3.141593'>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)'+3.1416; -3.1416'

指定進制

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)'int: 18; hex: 12; oct: 22; bin: 10010'>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'

千位分隔符

可以使用 "," 來作為千位分隔符:

>>> '{:,}'.format(1234567890)'1,234,567,890'

百分數顯示

>>> "progress: {:.2%}".format(19.88/22)'progress: 90.36%'

事實上,format 還支持更多的類型符號:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

其他技巧

占位符嵌套

某些時候占位符嵌套還是很有用的:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')'*****hello******'>>>>>> for num in range(5,12):...  for base in "dXob":...   print("{0:{width}{base}}".format(num, base=base, width=5), 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

作為函數使用

可以先不指定格式化參數,而是在不要的地方作為函數來調用:

>>> email_f = "Your email address was {email}".format>>> print(email_f(email="suodhuoty@gmail.com"))Your email address was sudohuoty@gmail.com

轉義大括號

當在字符串中需要使用大括號時可以用大括號轉義:

>>> " The {} set is often represented as { {0} } ".format("empty")' The empty set is often represented as {0} '

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 定南县| 临沭县| 扎兰屯市| 上饶县| 宣恩县| 玉山县| 汽车| 贺州市| 锡林郭勒盟| 社会| 荆州市| 侯马市| 城口县| 资兴市| 嘉祥县| 延长县| 桂阳县| 巴彦淖尔市| 蒲江县| 临江市| 合水县| 荃湾区| 宜君县| 昆山市| 成都市| 台北市| 金秀| 馆陶县| 蕉岭县| 禄劝| 肇东市| 安陆市| 石景山区| 阜南县| 荆门市| 南和县| 彭水| 柳林县| 彭水| 古蔺县| 景洪市|