Formate字符串格式化

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 或 [ ] 和 = 来代替以前的 %

format 函数可以接受不限个参数,位置可以不按顺序,第一种为常用写法!

第一种写法:

1 name = "齐天大圣{0},{1}是也"
2 s1 = name.format("孙悟空","美猴王")
3 print(s1)

第二种写法:

1 name = "齐天大圣{0},{1}是也"
2 s1 = name.format(*["孙悟空","美猴王"])
3 print(s1)

第三中写法:

1 name = "齐天大圣{x},{o}是也"
2 s1 = name.format(x="孙悟空",o="美猴王")
3 print(s1)

第四种写法:

1 name = "齐天大圣{x},{o}是也"
2 s1 = name.format(**{"x":"孙悟空","o":"美猴王"})
3 print(s1)

输出结果都是:齐天大圣孙悟空,美猴王是也

 

posted @ 2020-04-27 17:07  淳风港湾  阅读(2191)  评论(0编辑  收藏  举报