Python中字符串匹配方法format

使用python3的童鞋,不用看本文了,推荐使用f-string(点击查看)方法进行映射传参,使用更简单,可读性更强。


一、概述


  1. str.format() :映射传参、值格式化;
  2. 本文仅介绍其映射传参的用法,值格式化请自行Google/baidu;
  3. 优点
  • 不需要关注数据类型的问题
  • 可以接受无限个参数,位置可以不按顺序
  • 单个参数可以多次输出,参数顺序可以不相同
  • 填充方式灵活,对齐方式强大


二、映射--传参


  1. 位置:需要严格控制入参的位置
    '{0} {1}'.format("Hello", "XingZhe")
    -- >  'Hello XingZhe'
    
    '{0}_{0}'.format("Hello", "XingZhe")
    -- > 'Hello_Hello'
    
    '{}_{}'.format("Hello", "XingZhe”) 
    -- > 'Hello_XingZhe'
    
    '{1} {0} {1}'.format('Hello','XingZhe')
    -- > 'XingZhe Hello XingZhe'
    
  2. 关键字:代码可读性强;插入多个值只需传入1个参数;
    'I am {name}, age is {age}'.format(name = 'XingZhe', age = '29')
    -- > 'I am XingZhe, age is 29'
    
  3. 列表
    list1 = ['world','python']
    'Hello {names[0]}, I am {names[1]}'.format(names = list1)
    -- > 'Hello world, I am python'
    
    'Hello {0[0]}, I am {0[1]}'.format(list1)
    -- > 'Hello world, I am python'
    
  4. 字典:访问字典的key,不需要引号,format()的参数加星号表示模糊映射;
    site = {"name":"菜鸟教程", "url":"[www.runoob.com](http://www.runoob.com)"}
    "Hello {domain[name]}, I am {domain[url]}".format(domain = site)
    -- > 'Hello 菜鸟教程, I am [www.runoob.com](http://www.runoob.com)'
    
    "Hello {name}, I am {url}".format(**site)
    -- > 'Hello 菜鸟教程, I am [www.runoob.com](http://www.runoob.com)'
    
  5. class Sentence:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        def __str__(self):
            return 'The boy is {self.name}, age is {self.age} old'.format(self=self)
    
    print(Sentence('XZ', 29))
    -- > The boy is XZ, age is 29 old
    
  6. 下标
    names = ["xiaoming", "xiaoli","xiaohong"]
    ages = [28,16,9]
    
    "The bos is {0[2]}, age is {1[1]}".format(names,ages)
    -- > 'The bos is xiaohong, age is 16'
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容