写在前面
··· 日常开发中经常用到占位符进行字符串拼接, 普通用法基本满足开发场景,现对 两种占位符的高级用法进行归类总结
%
- %d int类型
demo'This is num %d'%10 # 普通用法 'This is num %5d'%10 # 普通用法 右对齐, 不足5位补足空格(-5代表左对齐)
'This is num %(key)d'%{'key': 10} # 关键字用法
- %s str类型
demo'This is str %s'%'demo' # 普通用法 'This is str %5s'%'demo' # 普通用法 右对齐, 不足5位补足空格(-5代表左对齐)
'This is str %(key)s'%{'key': 'demo'} # 关键字用法
- %f float类型
demo'This is float %f'%1 # 普通用法 默认6位小数 'This is float %.2f'%1 # 普通用法 保留2位小数 'This is float %10f'%1 # 普通用法 右对齐, 不足5位补足空格(-5代表左对齐)
'This is float %(key).2f'%{'key': 1} # 关键字用法
- %x 十六进制类型
demo'This is hex %x'%10 # 普通用法 'This is hex %10x'%10 普通用法 右对齐, 不足5位补足空格(-5代表左对齐)
'This is hex %(key)x'%{'key': 1} # 关键字用法
format
-
常见举例
{: s} str
{: d} int
{: f} float
非强绑定
… -
普通用法
>>> "{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'
-
设置参数
>>> "name: {name}, age: {age}".format({'name': 'haha', 61}) "name: 'haha', age: 61"
-
数字格式化