zoukankan      html  css  js  c++  java
  • python 字符串格式化—format

    Python2.6 开始,新增了一种格式化字符串的函数 str.format()。使用起来简单方便,不会遇到使用%时候格式的选择问题。

    按照参数默认顺序

    >>> "yesday is {}, today is {}".format("saturday", "sunday")
    'yesday is saturday, today is sunday'
    >>>
    

    指定参数顺序

    >>> "yesday is {0}, today is {1}, good day is {0}".format("saturday", "sunday")
    'yesday is saturday, today is sunday, good day is saturday'
    >>>
    

    指定参数名称

    #!/usr/bin/python
    
    s = "I am a {name}, and study {subject}".format(name="coder", subject="ES")
    print s
    

    output:

    I am a coder, and study ES

    使用字典做参数

    # dict
    d = {"name": "coder", "subject": "VUE"}
    s = "I am a {name}, and study {subject}".format(**d)
    print s
    

    output:

    I am a coder, and study VUE

    使用列表做参数

    # list
    l = ["coder", "big data"]
    s = "I am a {0}, and study {1}".format(*l)
    print s
    

    output:

    I am a coder, and study big data

    使用对象做参数

    class Orange(object):
            def __init__(self, v):
                    self.value = v
    
    
    orge = Orange(5)
    s = "The PH of an orange  is {.value}".format(orge)
    print (s)
    

    output:

    The PH of an orange is 5

  • 相关阅读:
    读书笔记-NIO的工作方式
    高精度运算-阶乘累积求和
    面试题-Java设计模式举例
    Web请求过程总结
    python 之栈的实现
    python之数据结构链表实现方式
    python 之分发包
    python之smtplib发邮件
    装饰器习题-接受参数的装饰器
    python之装饰器
  • 原文地址:https://www.cnblogs.com/lanyangsh/p/9865007.html
Copyright © 2011-2022 走看看