脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python format函数详谈

Python format函数详谈

2022-02-19 12:19我是NeroZhang Python

这篇文章主要介绍了Python中用format函数格式化字符串的用法,格式化字符串是Python学习当中的基础知识,希望能够给你带来帮助

Python字符串的format函数

format()函数用来收集其后的位置参数和关键字段参数,并用他们的值填充字符串中的占位符。通常格式如下:

'{pos or key : fill, align, sign, 0, width, .precision, type}'.format(para1...)

整个花括号是一个占位符,冒号前的位置或者关键字用来定位format函数的参数,冒号后面用来将该参数格式化,其中每一个都是可选项。

1.fill用来指定填充字符,默认为空格

2.align指定对齐方式:>为右对齐,<为左对齐,^为居中对齐

3.sign指定是否保留正负号:+为保留正负号,-为仅保留负号

4.宽度前面如果加0则表示用0填充

5.width指定宽度

6.precision指定精确度

7.type指定类型,如b为二进制,x为十六进制

一些示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#使用位置进行填充
print(
    'Hello,{0}. My name is {1}. How\'s it going?'.format('Hialry','Vergil')
    #Hello,Hialry. My name is Vergil. How's it going?
)
#若格式中未指定填充位置,将会按序填充
print(
    '{}--{}--{}--{}--{}--{}--{}'.format(1,2,3,4,5,6,7)
    #1--2--3--4--5--6--7
)
 
#使用关键字段进行填充
print(
    'I\'m {name1}, and I miss u so much, {name2}.'.format(name1='vergil',name2='hilary')
    #I'm vergil, and I miss u so much, hilary.
)
 
#使用下标填充
names=['hilary','vergil','nero']
places=['chengdu','shijiazhuang','tokyo']
print(
    'Hi, {names[0]}. I am {names[1]} and this is {names[2]}.'.format(names=names)
    #Hi, hilary. I am vergil and this is nero.
)
print(
    'Three people:{0[0]}, {0[1]}, {0[2]} from three places:{1[0]}, {1[1]}, {1[2]}.'.format(names,places)
    #Three people:hilary, vergil, nero from three places:chengdu, shijiazhuang, tokyo.
)
 
#进制转换
print(
    '{0:b}, {0:o}, {1:d}, {1:x}'.format(256,512)
    #100000000, 400, 512, 200
)
#逗号分隔
print(
    '{:,}'.format(12345678)
    #12,345,678
)
#浮点数格式
print(
    '{:+12.3f}'.format(3.14159265358979)
    #      +3.142
)
#对齐与填充
print(
    '{:>010}'.format(12), #右对齐,宽度10,填充0
    '{:0<+12.3f}'.format(-12.34567),#填充0,左对齐,保留正负号,宽度12,保留3位小数
    '|{:^10}|'.format(3) #,默认填充空格,居中对齐,宽度10
    #0000000012 -12.34600000 |    3     |
)

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/Hilavergil/article/details/79161590

延伸 · 阅读

精彩推荐