美文网首页
(二)字符串(2)格式化的字符串

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

作者: 费云帆 | 来源:发表于2018-12-17 09:37 被阅读0次

    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()时,它就是一个函数啦~~~~
    好比函数对象和函数....

    相关文章

      网友评论

          本文标题:(二)字符串(2)格式化的字符串

          本文链接:https://www.haomeiwen.com/subject/onxqkqtx.html