• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

7. python 字符串格式化方法(1)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

7. Python 字符串格式化方法(1)

承接上一章节,我们这一节来说说字符串格式化的另一种方法,就是调用 format()

  >>> template='{0},{1} and {2}'  
  >>> template.format ('a','b','c')  
  'a,b and c'  
  >>> template='{name1},{name2} and {name3}'  
  >>> template.format (name1='a',name2='b',name3='c')  
  'a,b and c'  
 >>> template='{name1},{0} and {name2}'  
  >>> template.format ('a',name1='b',name2='c')  
  'b,a and c'  
  >>>   

这里根据上面的例子说明一下

1. 替换的位置可以使用下标的来标记

2. 替换的位置可以使用名称来替换

下面我们来说说,在方法里面添加属性

  >>>import sys  
  >>> 'my {1[spam]} runs {0.platform}'.format(sys,{'spam':  
                           'laptop'})  
  'my laptop runs win32'  
  >>>   
  >>> 'my {config[spam]} runs {sys.platform}'.format(sys=sys,config={'spam':'laptop'})  
  'my laptop runs win32'  
  >>>   

上面两个例子里面,第一处读取了字符串,第二处读取 sys 里面的 platform 属性

下面再举一个例子,说明在表达式里面使用偏移量

  >>> aList=list('abcde')  
  >>> aList  
  ['a''b''c''d''e']  
  >>> 'first={0[0]} third={0[2]}'.format (aList)  
  'first=a third=c'  
  >>>   

注意:在使用偏移量的时候只能够是正整数,不能够使用负数,不能够使用代表区间正整数

  >>> aList=list('abcde')  
    
  >>> aList  
  ['a''b''c''d''e']  
  >>> 'first={0[0]} third={0[-1]}'.format (aList)  
  Traceback (most recent call last):  
    File "", line 1in   
      'first={0[0]} third={0[-1]}'.format (aList)  
  TypeError: list indices must be integers, not str  
  >>> 'first={0[0]} third={0[1:3]}'.format (aList)  
  Traceback (most recent call last):  
    File "", line 1in   
      'first={0[0]} third={0[1:3]}'.format (aList)  
  TypeError: list indices must be integers, not str  
  >>>   

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

上一篇:
7. python 字符串格式化方法(2)发布时间:2022-01-22
下一篇:
6. python 字符串格式化表达式发布时间:2022-01-22
热门推荐
    热门话题
    阅读排行榜

    扫描微信二维码

    查看手机版网站

    随时了解更新最新资讯

    139-2527-9053

    在线客服(服务时间 9:00~18:00)

    在线QQ客服
    地址:深圳市南山区西丽大学城创智工业园
    电邮:jeky_zhao#qq.com
    移动电话:139-2527-9053

    Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap