美文网首页Python
Python基础(21) - Format格式化字符串的详细方法

Python基础(21) - Format格式化字符串的详细方法

作者: xianling_he | 来源:发表于2020-03-01 16:21 被阅读0次

    字符串的format方法有机制制定参数方式

    1. 默认方式(传入参数与{} 一一对应)
    2. 命名参数与位置参数{2}

    详细描述字符串format方法如何格式化字符串

    • 不带命名参数的format
    s1 = 'Today is {}, the temprature is {} degrees.'
    
    print(s1.format('Saturday',24))
    
    image.png
    • 带上命名参数的format
    s2 = 'Today is {week}, the temprature is {degree} degrees.'
    
    print(s2.format(degree = 30, week = 'Monday'))
    
    image.png
    • 混合使用参数的format
    s3 = 'Today is {week}, the {} temprature is {degree} degrees.'
    print(s3.format('abcd',week = 'Sunday',degree=15))
    
    image.png
    • 混合使用参数format,使用索引引入到参数中
    1. 索引加入以后,参数会根据索引进行传参,不会根据自身顺序输出
    s4 = 'Today is {week}, the {0}, new {1} temprature is {degree} degrees.'
    print(s4.format('abcd','xyz',week = 'Sunday',degree=15))
    
    image.png
    s4 = 'Today is {week}, the {1}, new {0} temprature is {degree} degrees.'
    print(s4.format('abcd','xyz',week = 'Sunday',degree=15))
    
    image.png
    • 可以添加一个函数
    class Person:
        def __init__(self):
            self.age = 20
            self.name = 'Bill'
            
    person = Person()
    
    s5 = "My name is {p.name}, my age is {p.age}"
    print(s5.format(p = person))
    
    image.png

    总结

    Format方法使用一对大括号{} 制定字符串需要替换的部分,在大括号中可以使用数字标识符参数名设置相应的占位符

    加油 2020-3-1

    相关文章

      网友评论

        本文标题:Python基础(21) - Format格式化字符串的详细方法

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