python3 format函数 详解

python3 format函数 详解

‘三岁和你学编程,最白话的语言,最简单的理解,和你一起学习python’


听说你们想看 format()函数,今天他来了!

我怎么来??? —— 输出报错啦

 要输出一段含有整型的字符串怎么办?
 简单,不就是直接输出就好了
>>>a = '叁岁学编程'
>>>b = 10000
>>>c = 2025-5
>>> print('博客名:' + a + '访问数量:' + b + '时间:' + c)

>TypeError: can only concatenate str (not "int") to str

发生了什么?为什么输出不对,还报错了???
我们翻译一下:Typeerror: 只能将 str (不是“ int”)连接到 str

哦!str格式的后面只能够加str格式的不能够添加整型等其他格式
那一定要是数字怎么办???
而且这些是要随时可以改变的?

怎么办,猛男落泪

我来了! —— 字符串格式化

考虑到以上问题,我就诞生了

字符串类型格式化是运用字符串类型的重要内容,python格式化化有两种。
①同C语言printf( ) 函数的格式化方法
②format() 函数

我的今生前世 —— format()

我是一个新手在python2.6才出生的。
我的前身是C语言的printf( ) 函数

 用%d, %f, %s 等进行格式化输出
 我的“前身”在现在还可以使用,但是接下来的日子却前途渺茫咯!

我是谁? —— format()

format( )函数:执行字符串格式化操作。 调用此方法的字符串可以包含字符串字面值或者以花括号 {} 括起来的替换域。 每个替换域可以包含一个位置参数的数字索引,或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替换为对应参数的字符串值。

>>>"The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
>>>'博客名:{} 访问数量:{} 时间:{} '.format(a,b,c) 
#范例同上
>博客名:叁岁学编程 访问数量:10000 时间:2025 

使用格式为下:
< 模板字符串>.format(<逗号分隔的参数>)
模板字符串由一系列的槽组成,用来控制修改字符串中嵌入值的出现位置。
①在{}中有序号的,按照顺序走
②没有序号的按照序号走
在这里插入图片描述
在这里插入图片描述
③按照对应的名称进行排序

>>>'Coordinates: {latitude}, {longitude}'
                 .format(latitude='37.24N', longitude='-115.81W')
>'Coordinates: 37.24N, -115.81W'

format()成长中

函数format() 是接替%格式化的他的内容比较丰富,功能强大而且再进一步发展中

  • 对齐文本并指定宽度:
>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

具体含义:
在这里插入图片描述

  • 更换%+f,%-f以及与指定的标志:% f:
>>> '{:+f}; {:+f}'.format(3.14, -3.14) 
 # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) 
 # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) 
 # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
  • 一些其他的方法:
    在这里插入图片描述
    在这里插入图片描述

进化了的我 —— 3.7以后版本

在3.7版本以后简化了我的用法:
注意注意是3.7版本以后的,在之前版本会报错的!

点击查看:f字符串和str.format表达式之间的区别
一些用法的展示:

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."

>>> f"He said his name is {repr(name)}."  
># repr() is equivalent to !r
"He said his name is 'Fred'."

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  
># nested fields
'result:      12.35'

>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" 
> # using date format specifier
'January 27, 2017'

>>> number = 1024
>>> f"{number:#0x}"  # using integer format specifier
'0x400

该用法简化了许多程序
把 字符串.format( , ) 进行了简化变成了 f‘字符串{变量等}’

错误示范:
与常规字符串文字共享相同语法的结果是,替换字段中的字符不得与外部格式化的字符串文字中使用的引用冲突:

>>>f"abc {a["x"]} def"    
 error: outer string literal ended prematurely
>>>f"abc {a['x']} def"   
 workaround: use different quoting

格式表达式中不允许反斜杠,并且会引发错误:

>>>f"newline: {ord('\n')}"  
 raises SyntaxError

解决办法:创建一个临时变量再导入

>>>newline = ord('\n')
>>>f"newline: {newline}"
'newline: 10'

参考资料:
python官网:https://www.python.org/dev/peps/pep-0498/#id41
https://docs.python.org/3/library/string.html#formatspec
https://www.python.org/dev/peps/pep-0498/#differences-between-f-string-and-str-format-expressions

发布了38 篇原创文章 · 获赞 116 · 访问量 7583

猜你喜欢

转载自blog.csdn.net/weixin_45623093/article/details/105069073