计算机二级python备考刷题知识点总结(二)
1、center()
语法:str.center(width,fillchar)
注:fillchar必须要用引号引起了
center()返回一个原字符串居中,并使用填充字符填充到长度为width的新字符串,默认填充字符为空格
2、format()
format是字符串内嵌的一个方法,用于格式化字符串。以大括号{}来标明被替换的字符串。
(1)按照{}的顺序依次匹配括号中的值
s = '{} is a {} language'.format('python','program') print(s) s = '{} is a {} language'.format('python') print(s) #运行结果 python is a program language Traceback (most recent call last): File "/Users/xx/mysystem/format用法.py", line 3, in <module> s = '{} is a {} language'.format('python') IndexError: tuple index out of range
(2)通过索引的方式去匹配参数
s = '{0} is a {1} language'.format('python','program') print(s) s = '{1} is a {0} language'.format('python','program') print(s) #运行结果 python is a program language program is a python language
(3)通过参数名来匹配参数
s = '{name} is a {type} language'.format(name='python',type='program') print(s) name = 'Mary' s = f"my name is {name}" print(s) #运行结果 python is a program language my name is Mary
(4)混搭使用
索引、 参数名混搭进行匹配,注意:命名参数必须写在后边,不然会编译出错!其次,索引和默认格式不可以混合使用
s = '{} is a {type} language'.format('python',type='program') print(s) s = '{name} is a {} language'.format(name='python','program') print(s) #运行结果 python is a program language File "/Users/mysystem/format用法.py", line 3 s = '{name} is a {} language'.format(name='python','program') ^ SyntaxError: positional argument follows keyword argument
参考:https://blog.csdn.net/qq_42855293/article/details/118480087
感谢好的帖子分享,非常详细。