(二)字符串(2)格式化的字符串

1.字符串的"格式化"---"格式化"的字符串,用占位符(例如"%s",这种方法已经过时)来表示位置:

>>> "I like %s" % "Python"
'I like Python'

2.format()函数---s.format(args,kwargs),"args"表示一种参数,"**kwargs"表示另一种参数.

  • 实例1:更改上面的例子
>>> "I like {}".format("Python")
'I like Python'
  • 实例2:使用索引:
>>> "I like {0} and {1}".format("Python","Canlaoshi")
'I like Python and Canlaoshi'

更改索引位置:

>>> "I like {1} and {0}".format("Python","Canlaoshi")
'I like Canlaoshi and Python'
  • 实例3:更改对齐方式,默认是左对齐,"<"表示右对齐,"10"和"15"表示这个字符串的长度
>>> "I like {0:10} and {1:<15}".format("Python","Canlaoshi")
'I like Python     and Canlaoshi   

居中对齐(符号"^"):

>>>"I like {0:^10} and {1:^15}".format("Python","Canlaoshi")
'I like   Python   and    Canlaoshi   '

截取特定的字符串长度:

#".2"表示只取前面两个字符,"^10.."表示居中对齐,字符串长度为10,但只截取前面3个字符
>>> "I like {0:.2} and {1:^10.3}".format("Python","Canlaoshi")
'I like Py and    Can    '

实例4:"格式化"的数字

>>> "She is {0:d} year old and the breast is {1:f}".format(20,90.123456)
'She is 20 year old and the breast is 90.123456'

注意下,直接用"d"和"f"是没办法表示数字的:

>>> "She is {d} year old and the breast is {f}".format(20,90.123456)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    "She is {d} year old and the breast is {f}".format(20,90.123456)
KeyError: 'd'

保留两个小数,默认右对齐(字符串默认是左对齐):

>>> "She is {0:4d} year old and the breast is {1:6.2f}".format(20,90.123456)
'She is   20 year old and the breast is  90.12'

再加一个"0":长度不够,用0补充

>>> "She is {0:04d} year old and the breast is {1:06.2f}".format(20,90.123456)
'She is 0020 year old and the breast is 090.12'

实例5:传入"指针"(我觉得python的"变量"称为"指针"或"标签"更为贴切)
以下实例,脱离了{0},{1}限制...

>>> "I like {lang} and {teacher}".format(lang="Python",teacher="Canlaoshi")
'I like Python and Canlaoshi'

"格式化"的字典---".format(**kwargs)"

>>> data={"name":"Canlaoshi",'age':20}
>>> "{name} is {age} years old.".format(**data)
'Canlaoshi is 20 years old.'
>>> 

补充:
str不加括号,表示的就是str对象,故可以使用help(str),查看对象的属性和方法,当变成str()时,它就是一个函数啦~~~~
好比函数对象和函数....

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 两本不错的书: 《Python参考手册》:对Python各个标准模块,特性介绍的比较详细。 《Python核心编程...
    静熙老师哈哈哈阅读 3,388评论 0 80
  • Python史上最全开发总结(转自静熙老师哈哈哈) 两本不错的书: 《Python参考手册》:对Python各个标...
    春风在抱阅读 773评论 1 4
  • 说实话,我虽然是一个快迈向法定结婚年龄的人,但至今尚未能清楚地理解爱情的定义。即使,看过了很多的青春偶像剧和狗血的...
    折耳落木阅读 217评论 0 1
  • 第一步,首先看官网文档啊 1. 添加jar MiPush_SDK_Client_3_6_2.jar 到 lib...
    chengs阅读 705评论 0 0
  • 诺大的城市!孤独的灵魂 趁时光正好,做自己想做的事! 去学街舞,跳遍全国所有自己想去的地方…… 就这样
    lemon031阅读 142评论 0 0