【Python基础6】格式化字符串

常用方法举例

使用%设置字符串格式,适用场景相对单一

>>> "%s, %s!" % ('Hello','world',)
'Hello, world!'
>>>

使用f开头的格式化(python3上支持,python2不支持)

Python 3.6.8 (default, May 26 2019, 10:58:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Foodly"
>>> print(f"hello {name}")
hello Foodly
>>> print(f"the {name} has {len(name)} char")
the Foodly has 6 char
>>>
[root@CSDN ~]#python2
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Foodly"
>>> print(f"hello {name}")
  File "<stdin>", line 1
    print(f"hello {name}")
                        ^
SyntaxError: invalid syntax
>>>

使用format方法设置字符串格式,应用场景更广

>>> "{},{} and {}".format(1,2,3)
'1,2 and 3'
>>> "{2},{0} and {1}".format(2,3,1)
'1,2 and 3'
>>> from math import pi
>>> "pi={value:.2f}".format(value=pi)
'pi=3.14'
>>> #当变量名称一致时可以简写
>>> f"{pi:.2f}"
'3.14'
>>> 

要在最终结果中包含花括号则需要两对花括号

>>> '{{:{}}}'.format(4)
'{:4}'
>>> '{{:{}}}'.format(4).format('xl')
'xl  '
>>> 

像上面的‘%s’和{pi:.2f}里面的s和f是类型说明符

类型含义
b将整数表示为二进制数
c将整数解读为Unicode码点
d将整数视为十进制数处理(整数默认使用的说明符)
e科学计数法表示小数(用e来表示指数)
E与e相同,E表示指数
f将小数表示为定点数
F与f相同,特殊值用大写表示
g自动在定点表示和科学表示法之间做出选择,这是默认的小数说明符,但在默认的情况下至少有1位小数
G与g相同,但使用大写表示特殊值
n与g相同,但插入随区域而异的数字分隔符
o将整数表示为八进制
s字符串默认说明符
x将整数表示为十六进制
X与x相同,使用大写字母
%将数表示为百分百值

宽度、精度和千分位分隔符

>>> "{num:5}".format(num=3)
'    3'
>>> "{name:5}".format(name='xl')
'xl   '
>>> f"{pi:.3f}"
'3.142'
>>> "one billion is {:,}".format(10*10000*10000)
'one billion is 1,000,000,000'
>>> 

符号、对其和0填充

>>> '{:05.2f}'.format(pi)
'03.14'
>>> print('{0:<12.2f}\n{0:^12.2f}\n{0:>12.2f}'.format(pi))
3.14        
    3.14    
        3.14
>>> '{:#^15}'.format('bb')
'######bb#######'
>>> '{:a^15}'.format('bb')
'aaaaaabbaaaaaaa'
>>> '{:#15.2f}'.format(pi)
'           3.14'
>>> '{:#^15.2f}'.format(pi)
'#####3.14######'
>>> 
>>>> '{:.2f}'.format(+pi)
'3.14'
>>> '{:.2f}'.format(-pi)
'-3.14'
>>> '{:+.2f}'.format(-pi)
'-3.14'
>>> '{:+.2f}'.format(+pi)
'+3.14'
>>> '{:+.2f}'.format(pi)
'+3.14'
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值