源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python字符串格式化的方法(两种)

  • 时间:2021-06-16 13:56 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python字符串格式化的方法(两种)
本文介绍了Python字符串格式化,主要有两种方法,分享给大家,具体如下 用于字符串的拼接,性能更优。 字符串格式化有两种方式:百分号方式、format方式。 百分号方式比较老,而format方式是比较先进的,企图替代古老的方式,目前两者共存。 [b]1、百分号方式[/b] 格式:%[(name)][flags][width].[precision]typecode [list] [*](name)    可选,用于选择指定的key[/*] [*]flags        可选,可供选择的值有: [list]
  • +  右对齐:正数的加正号,负数的加负号[/*] [*]-  左对齐:正数前没有负号,负数前加负号[/*] [/list]
  • [*]width    可选,占有宽度[/*] [*].precision    可选,小数点后保留的位数[/*] [*]typecode     必选 [list]
  • s,获取传入的对象__str__方法的返回值,并将其格式化到指定位置[/*] [*]r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置[/*] [*]c,整数:将数字转换成其unicode对应的值,10进制范围为0 <= i <=1114111[/*] [*]o,将整数转换成八进制表示,并将其格式化到指定位置[/*] [*]x,将整数转换成16进制,并将其格式化到指定位置[/*] [*]d,将整数,浮点数转化为十进制表示,并将其格式化到指定位置 [/*] [/list]
  • [/list]
    >>> s = 'i am %s,age %d' %('cai',18)
    
    >>> print(s)
    
    i am cai,age 18
    
     
    
    >>> s = 'i am %(n1)s,age %(n2)d' %{'n1':'cai','n2':18}
    
    >>> print(s)
    
    i am cai,age 18
    
     
    
    >>> s = 'i am %(n1)+10s,age %(n2)d' %{'n1':'cai','n2':18}
    
    >>> print(s)
    
    i am    cai,age 18
    
     
    
    >>> s = 'i am %(n1)+10s,age %(n2)10d' %{'n1':'cai','n2':18}
    
    >>> print(s)
    
    i am    cai,age     18
    
     
    
    >>> s = "i am %.3f abcd" %1.2
    
    >>> print(s)
    
    i am 1.200 abcd 
    
    [b]2、format方式、[/b]
    i1 = "i am {},age {} ,{}".format('cairui',18,'kk')
    
    print(i1)
    
      i am cairui,age 18 ,kk
    
     
    
    i1 = "i am {0},age {1} ,{0}".format('cairui',18)
    
    print(i1)
    
      i am cairui,age 18 ,cairui
    
     
    
    i1 = "i am {name},age {age} ,{name}".format(name='cairui',age=18)
    
    print(i1)
    
      i am cairui,age 18 ,cairui
    
     
    
    i1 = "i am {:s},age {:d} ,{:f}".format('cairui',18,6.1)
    
    print(i1)
    
      i am cairui,age 18 ,6.100000 
    
    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
    • 全部评论(0)
    联系客服
    客服电话:
    400-000-3129
    微信版

    扫一扫进微信版
    返回顶部