Format

Format String Syntax

1
2
3
4
5
6
7
8
replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>

field_name

Format

  • arg_name: 默认为integer类型,从0到1; integer表示参数位置,identifier表示参数的key值
  • attribute: 表示参数对象的属性
  • element_index: 表示参数对象的index值

Example

1
2
3
4
5
6
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"From {} to {}" # Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.

conversion

Format

  • !s : 调用str()
  • !r : 调用repr()
  • !a : 调用ascii()

Example

1
2
3
"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
"More {!a}" # Calls ascii() on the argument first

format_spec

  • format_spec中不能包含conversion,内嵌format_spec
  • format specification(说明书)率属于语言—Format Specification Mini-Language

format

1
2
3
4
5
6
7
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" |

非type字段

  • fill: 表示任何填充的字符值

  • align: <, >, ^, 分别表示左对齐,右对齐,居中; =, 必须确保”the input is a numeric type.”,否则抛出异常

  • sign: + 表示正数前加上”+”符号, - 表示负数前加上”-“符号, “空”表示在正数前加上空格

  • #: #仅仅适用于binary, octal, hexadecimal,输出为0b, 0o, 0x格式

  • 0: 仅仅适用于整型,同align为=的用法

  • ,: 用于千分位分割用法

  • width: 默认的width为input value长度

  • precision: 保留小数位数,不允许在整型中使用

type字段

  • s: 默认的字符串格式,默认值
  • b: binary格式
  • c: 将整型转为相应的unicode码,之后再填充,适用于integer
  • d: Decimal格式
  • o: Octal格式
  • x: Hex格式,小写
  • X: Hex格式,大写
  • n: 类似d,但是使用本地

参考