python中.format()方法用法详解
  TEZNKK3IfmPf 2023年11月13日 33 0

format语法格式:

        str.format()
        str是指字符串实例对象,常用格式为‘ ’.format()

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

format参数格式

'{[index][ : [fill] align][sign][#][width][.precision][type]} {……}{……} '.format()
注意,格式中的[ ]内的参数都是可选参数,可以使用也可以不使用

  • index:指定冒号**:**后面出现的参数在‘format()’中的索引值,如果没有,则以format()中的默认顺序自动分配
  • fill:指定空白处的填充符。
  • align:指定数字的对齐方式:
align 含义
< right-aligned 左对齐(对于大部分对象时为默认)
> right-aligned 右对齐 (对于数字时为默认)
= 数据右对齐,同时将符号放置在填充内容的最左侧,该选项只对数字类型有效
^ 数据居中,此选项需和 width 参数一起使用
  • sign:指定有无符号数,此参数的值以及对应的含义如表所示
sign 参数 含义
+ 正数前面添加 ‘ + ’ ,负数前面加 ‘ - ’
- 正数前面不添加 ‘ + ’ ,负数前面加 ‘ - ’
space 正数前面添加 ‘ 空格 ’ ,负数前面加 ‘ - ’
# 对于二进制数、八进制数和十六进制数,使用此参数,各进制数前会分别显示 0b、0o、0x前缀;反之则不显示前缀
  • width:指定输出数据时所占的宽度
  • . precision:如果后面存在type参数,则指的是保留小数的位数,如果type参数不存在,则是指有效数字的位数
  • type:指定输出数据的具体类型

python中.format()方法用法详解

一、简单使用方法

1.无参数

  • foramt会把参数按位置顺序来填充到字符串中,第一个参数是0,然后1 ……
  • 也可以不输入数字,则会按照顺序自动分配,而且一个参数可以多次插入

示例代码:

name = '张三'
age = 25
sex = '男'

print('{}、{}、{}'.format(name, age, sex))  #  占位符不指定顺序
print('{0}、{1}、{2}'.format(name, age, sex)) #  占位符制定顺序
print('{0}、{2}、{1}'.format(name, age, sex)) #  换一下顺序试试
print('{0}、{2}、{1}、{0}、{2}、{1}'.format(name, age, sex))

运行结果:

python中.format()方法用法详解

2. key value

示例代码:

name1 = '张三'
age1 = 25
sex1 = '男'

print('name:{name}、age={age}、sex:{sex}'.format(name=name1, age=age1, sex=sex1))
print('name:{name}、sex:{sex}、age={age}'.format(name=name1, age=age1, sex=sex1))

运行结果:

python中.format()方法用法详解

3. 列表

示例代码:

lst1 = ['张三', '男', 25]
lst2 = ['李四', '男', 28]

print('name:{Lst[0]},sex:{Lst[1]},age:{Lst[2]}'.format(Lst=lst1))
print('name:{0[0]},sex:{0[1]},age:{0[2]}'.format(lst1))
print('name:{0[0]},sex:{0[1]},age:{0[2]}'.format(lst2))
print('name:{0[0]},sex:{0[1]},age:{0[2]}'.format(lst1, lst2))
print('name:{1[0]},sex:{1[1]},age:{1[2]}'.format(lst1, lst2))
print('name:{0[0]},sex:{0[1]},age:{0[2]},name:{1[0]},sex:{1[1]},age:{1[2]}'.format(lst1, lst2))

运行结果:

python中.format()方法用法详解

4. 字典

示例代码:

dic1 = {'name': '张三', 'sex': '男', 'age': 25}
dic2 = {'name': '李四', 'sex': '男', 'age': 28}

print('name:{Dic[name]},sex:{Dic[sex]},age:{Dic[age]}'.format(Dic=dic1))
print('name:{name},sex:{sex},age:{age}'.format(**dic2))

运行结果:

python中.format()方法用法详解

5. 类

示例代码:

class Info(object):
    name = '张三'
    sex = '男'
    age = 25


print('name:{info.name},sex:{info.sex},age:{info.age}'.format(info=Info))

运行结果:

python中.format()方法用法详解

6. 魔法参数

*args表示任何多个无名参数,它是一个tuple or list;**kwargs表示关键字参数,它是一个 dict。

 示例代码:

lst = [',', '.']
dic = {'name': '张三', 'sex': '男', 'age': 25}

print('name:{name}{0}sex:{sex}{0}age:{age}{1}'.format(*lst, **dic))

运行结果:

python中.format()方法用法详解

7.使用感叹号!

  • !r:引用__repr__
  • !s: __str__
  • !a:acsii模式

示例代码1:

class Data(object):
    data = 'my is test data!'

    def __str__(self):
        return 'my is __str__!'

    def __repr__(self):
        return 'my is __repr__!'


# Old
print('%s' % Data().data)
print('%s, %r' % (Data(), Data()))

print("*" * 100)

# New
print('{}'.format(Data.data))
print('{}'.format(Data().data))
print('{0!s}, {0!r}'.format(Data))
print('{0!s}, {0!r}'.format(Data()))

运行结果:

python中.format()方法用法详解

 <conversion>组件,数据强制转换 str() 强制转换方法。

示例代码2:  【一般类型对于<conversion>组件是不起作用的】

s = 12345
print(s, type(s))

a = '{0!a}'.format(s)
b = '{0!s}'.format(s)
c = '{0!r}'.format(s)

print(a, type(a))
print(b, type(b))
print(c, type(c))

运行结果:

python中.format()方法用法详解

示例代码3:

import string

print("Harold's a clever {0!s}".format(string) == "Harold's a clever {0}".format(str(string)))
print("Harold's a clever {0!s}".format(string))

# '{0!s}'.format(42) # !s 转换为str()'42'
# '{0!r}'.format(42) # !r 转换为repr()'42'
# '{0!a}'.format(42) # !a 转换为ascii()'42'

运行结果:

python中.format()方法用法详解

8.__format__() 用法

        __format__()传参方法:someobject.__format__(specification)

  specification为指定格式,当应用程序中出现"{0:specification}".format(someobject)或format(someobject, specification)时,会默认以这种方式调用。

  当specification为" "时,一种合理的返回值是return str(self),这为各种对象的字符串表示形式提供了明确的一致性。

  注意:"{0!s}".format()和"{0!r}".format()并不会调用__format__()方法,他们会直接调用__str__()或者__repr__()。

8.1 自定义__format__()格式

示例代码:

class FormatTest(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __format__(self, specification):
        if specification == "":
            return str(self)

        strformat = specification.replace("%s", self.name).replace("%r", self.age)
        return strformat


if __name__ == "__main__":
    people = FormatTest("zhangsan", "25")
    print(people)
    print("{}".format(people))
    print("{0:%s-%r}".format(people))
    print(format(people, "%s-%r"))

运行结果:

python中.format()方法用法详解

8.2格式化对象中的集合

示例代码:

class FormatTest(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __format__(self, specification):
        if specification == "":
            return str(self)

        str_format = specification.replace("%s", self.name).replace("%r", self.age)
        return str_format


class Handle(object):
    def __init__(self, *people):
        self.peoples = []
        self.peoples = list(people)

    def __format__(self, specification):
        if specification == "":
            return str(self)

        return ",".join("{:{fs}}".format(people, fs=specification) for people in self.peoples)


if __name__ == "__main__":
    res = Handle(FormatTest("zhangsan", "25"), FormatTest("lisi", "26"), FormatTest("wangwu", "27"))
    print(res)
    print("{:%s-%r}".format(res))

运行结果:

python中.format()方法用法详解

二、参数使用方法

示例代码1:

#  python :^:代表居中显示,数字567,位数width=10,fill=*(填充符为*)
print('{:*^10}'.format(567))

运行结果:

python中.format()方法用法详解

 示例代码2:

# python :0是填充符,2是width,表示位数为2
print('{:02}:{:02}:{:02}'.format(13, 4, 57))
print('{:05}:{:05}:{:05}'.format(13, 4, 57))

运行结果:

python中.format()方法用法详解

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   34   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   27   0   0 python
  TEZNKK3IfmPf   2024年05月31日   27   0   0 python
TEZNKK3IfmPf