python字符串格式化
Format
Format String Syntax
1 | replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" |
field_name
Format
- arg_name: 默认为integer类型,从0到1; integer表示参数位置,identifier表示参数的key值
- attribute: 表示参数对象的属性
- element_index: 表示参数对象的index值
Example
1 | "First, thou shalt count to {0}" # References first positional argument |
conversion
Format
- !s : 调用str()
- !r : 调用repr()
- !a : 调用ascii()
Example
1 | "Harold's a clever {0!s}" # Calls str() on the argument first |
format_spec
- format_spec中不能包含conversion,内嵌format_spec
- format specification(说明书)率属于语言—Format Specification Mini-Language
format
1 | format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] |
非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,但是使用本地
参考
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 狂想写作本!
评论