前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 字符串格式化方法

Python 字符串格式化方法

作者头像
Python知识大全
发布2020-02-13 15:00:34
3390
发布2020-02-13 15:00:34
举报

字符串格式化方法

阅读本文需要2分钟

一种常用字符串格式化的方法,就是调用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 1, in   
      '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 1, in   
      'first={0[0]} third={0[1:3]}'.format (aList)  
  TypeError: list indices must be integers, not str  
  >>>

1

END

岁月有你,惜惜相处

发现更多精彩

关注公众号

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python 知识大全 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档