我是靠谱客的博主 野性鸭子,这篇文章主要介绍Python简单函数记录——format格式化函数,现在分享给大家,希望可以做个参考。

个人记录,用到的东西,怕忘。

 

函数str.format(),对str进行格式化。

使用大括号{}作为占位符,代替c里面的%2d,%5f之类的来进行格式化操作。

实例:

复制代码
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#这一段摘自runoob教程 >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world' #就是说存在一个以上的占位符的时候,占位符中间没东西代表默认顺序,需要改变顺序的时候要指定位置。 #format()里面也可以传入list作为参数。 >>> x="1234567" >>> '{0}/{0}'.format(x) '1234567/1234567' #当需要进行字符串截断的时候: #单个字符可以直接截断取出来 >>> '{0[2]}/{0}'.format(x) '3/1234567' #多个字符要在后面这么截 >>> '{0:.3}/{0}'.format(x) '123/1234567' #可以定义增加空格站位,这个例子里面前面的5代表五格,所以截出123后空了两格 >>> '{0:5.3}/{0}'.format(x) '123 /1234567' #至于如何从中间截断字符串,我没找到,暂时也不需要用到,以后再补 #保留小数格式: >>> '{0:.2f}%'.format(92.4567) '92.45%' #空位补0: >>> '{0:02d}%'.format(1) '02' #这一段也是菜鸟教程的,用format设置参数 print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com")) # 通过字典设置参数 site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['菜鸟教程', 'www.runoob.com'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

官方文档:https://docs.python.org/3/library/string.html#formatstrings

菜鸟教程:https://www.runoob.com/python/att-string-format.html

最后

以上就是野性鸭子最近收集整理的关于Python简单函数记录——format格式化函数的全部内容,更多相关Python简单函数记录——format格式化函数内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部