zoukankan      html  css  js  c++  java
  • Python--字符串格式化

    1、字符串格式化

    print("我叫%s,今年%d岁"%("alex",25))
    
    #打印
    
    我叫alex,我今年25岁

    使用%,字符串为%s,数字为%d

    2、str.format()  格式化字符串函数,主要用{ } 与 : 代替原有的%

    i.有关位置设定

    s1 = "我叫{},今年{}岁".format("alex",25)  # 不设定位置,按默认顺序
    
    s2 = "我叫{0},今年{1}岁".format("alex",25)  # 设定位置
    
    s3 = "我叫{0},今年{1}岁。  --{0}".format("alex",25)  # 设定位置
    
    #打印:
    
    我叫alex,今年25岁
    
    我叫alex,今年25岁
    
    我叫alex,今年25岁。  --alex

    ii.设置参数

    s3 = "名字:{name},年龄:{age}".format(name="alex", age=25)  # 设定参数
    
    dic = {"name": "alex", "age": 25}
    s4 = "名字:{name},年龄:{age}".format(**dic)  # 字典设定参数
    
    stu_list = ["alex", 25]
    s5 = "名字:{0[0]},年龄:{0[1]}".format(stu_list)  #列表设定参数
    
    #打印:
    名字:alex,年龄:25
    名字:alex,年龄:25
    名字:alex,年龄:25

    iii.传入对象:

    class AssignValue(object):
        def __init__(self, value):
            self.value = value
    my_value = AssignValue(6)
    print('value 为: {0.value}'.format(my_value))  # "0" 是可选的
    
    #打印:
    value 为: 6
  • 相关阅读:
    LSMW TIPS
    Schedule agreement and Delfor
    Running VL10 in the background 13 Oct
    analyse idoc by creation date
    New Journey Prepare
    EDI error
    CBSN NEWS
    Listen and Write 18th Feb 2019
    Microsoft iSCSI Software Target 快照管理
    通过 Microsoft iSCSI Software Target 提供存储服务
  • 原文地址:https://www.cnblogs.com/hexiaorui123/p/9949507.html
Copyright © 2011-2022 走看看