首页 > 其他 > 详细

Formate字符串格式化

时间:2020-04-27 17:39:43      阅读:53      评论:0      收藏:0      [点我收藏+]

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)

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

 

Formate字符串格式化

原文:https://www.cnblogs.com/chunfenggangwan/p/12788026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!