24 - 格式化字符串
  7hRIHxbwwFZR 2024年02月23日 144 0

格式化字符串

笔者认为格式化字符串 (formatted string) 在任何语言里都值得单独拿出来做个笔记,因为它是编程中控制输出的重要一环。

Formatted String Literals (f-string)

官网的翻译为 “格式化字符串字面值”。比较常用的格式化方法。

在字符串前加上前缀 fF ,通过 {expression} 替代区域 (replacement field),把需要表达的内容添加到字符串内。

>>>print(f'1 + 1 = {1 + 1}')
1 + 1 = 2
>>>print(f'1 + 1 = {1 + 1:3d}')
1 + 1 =   2
>>>print(f'3 / 2 = {3 / 2:4.1f}')
3 / 2 =  1.5

Python 会计算 替代区域 表达式内的内容,然后插入到原字符串内进行打印。在 替代区域 中可以加入 format specifiers 来格式化插入的方式。

替代区域(replacement field) 的语法格式:

replacement_field ::=  "{" [field_name] [debug] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
debug             ::=  "="
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  format-spec:format_spec

(format_spec) 语法格式:

format_spec     ::=  [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

笔者认为这样的语法格式还是很清晰的。至于具体每个缩写代表,笔者建议直接翻看文档,这里就不直接照抄了。常见的选项见多了就会了,见不到的人不会需要那些内容。

字符串 format() 方法

format() 方法 f-string 很类似,不过它实现了字符串与 替代区域 的拆分。

调用此方法的字符串可以包含字符串字面值或者以花括号 {} 括起来的替换域。

每个替换域可以包含一个位置参数的数字索引,或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替换为对应参数的字符串值。

>>>a = "abc{0}{1}"
>>>print(a.format('x', 'y'))
abcxy
>>>print(a.format('cool', 'wa'))
abccoolwa
>>>b = 'yoo{yes}{no}'
>>>b.format(yes='haha', no='nono')
'yoohahanono'

printf 风格格式化

Python 过去使用这种格式化规则,但现在 Python 建议转到 f-string 或 format() 方法。不过笔者仍然看到很多人使用这种方法。

>>>print('%(language)s has %(number)03d quote types.' %
...      {'language': "Python", "number": 2})
Python has 002 quote types.
>>>print('%s has %03d quote types.' %("Python", 2))
Python has 002 quote types.

简单的来说就是

  1. %["("keywords")"][flag][width]["." precision][type] 在字符串中占位,
  2. 然后用 % 运算符将需要的内容带入字符串
    • 如果提供 keywords,则 % 需要跟字典
    • 否则 % 需要跟元组。

手动设置输出格式

笔者这里记录一下除了上述三种格式化方法以外,还可以自己设定输出格式。

笔者才疏学浅,暂时没见过也用不上这种方式,因此不多记录。


ref:
Python docs: Fancier Output Formatting
Python docs: Format Specification Mini-Language
Python docs: python 3.8 - f-string support for self-documenting and debugging
Python docs: str.format()
Python docs: printf-style string formatting

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年02月23日 0

暂无评论

推荐阅读
  2Fnpj8K6xSCR   2024年05月17日   101   0   0 Python
  xKQN3Agd2ZMK   2024年05月17日   70   0   0 Python
  fwjWaDlWXE4h   2024年05月17日   38   0   0 Python
  YpHJ7ITmccOD   2024年05月17日   39   0   0 Python
7hRIHxbwwFZR