非常教程

Python参考手册

Python format 格式化函数

Python format 格式化函数

Python format 格式化函数

Python format 格式化函数

Python 字符串


Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {}: 来代替以前的 %

format 函数可以接受不限个参数,位置可以不按顺序。

实例

>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'

也可以设置参数:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="非常教程", url="www.verydoc.net")) # 通过字典设置参数 site = {"name": "非常教程", "url": "www.verydoc.net"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['非常教程', 'www.verydoc.net'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果为:

网站名:非常教程, 地址 www.verydoc.net
网站名:非常教程, 地址 www.verydoc.net
网站名:非常教程, 地址 www.verydoc.net

也可以向 str.format() 传入对象:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是可选的

输出结果为:

value 为: 6

数字格式化

下表展示了 str.format() 格式化数字的多种方法:

>>> print("{:.2f}".format(3.1415926));
3.14
数字格式输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:>10d}         13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d}     13 中间对齐 (宽度为10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -  (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

此外我们可以使用大括号 {} 来转义大括号,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- print ("{} 对应的位置是 {{0}}".format("verydoc"))

输出结果为:

verydoc 对应的位置是 {0}

Python format 格式化函数

Python 字符串

Python format 格式化函数
Python

Python 是一种面向对象的解释型计算机程序设计语言,由荷兰人 Guido van Rossum 于1989年发明,第一个公开发行版发行于1991年。 Python 是纯粹的自由软件, 源代码和解释器 CPython 遵循 GPL 协议。Python 语法简洁清晰,特色之一是强制用空白符( white space )作为语句缩进。

主页 https://www.python.org/
源码 https://github.com/python/cpython
版本 2.7
发布版本 2.7.13

Python目录

1.内置常量 | Built-in Constants
2.内置例外 | Built-in Exceptions
3.内置函数 | Built-in Functions
4.内置类型 | Built-in Types
5.编译器 | Compiler
6.加密 | Cryptography
7.数据压缩 | Data Compression
8.数据持久性 | Data Persistence
9.数据类型 | Data Types
10.调试和分析 | Debugging & Profiling
11.开发工具 | Development Tools
12.文件和目录访问 | File & Directory Access
13.文件格式 | File Formats
14.构架 | Frameworks
15.输入 | Importing
16.输入/输出 | Input/ouput
17.国际化 | Internationalization
18.网络 | Internet
19.网络数据 | Internet Data
20.翻译 | Interpreters
21.语言 | Language
22.记录 | Logging
23.Mac OS
24.MS Windows
25.多媒体 | Multimedia
26.联网 | Networking
27.数字与数学 | Numeric & Mathematical
28.操作系统 | Operating System
29.可选操作系统 | Optional Operating System
30.限制执行 | Restricted Execution
31.运行 | Runtime
32.SGI IRIX
33.软件包装与分销 | Software Packaging & Distribution
34.字符串 | String
35.结构化标记 | Structured Markup
36.Tk
37.Unix
38.Python 简介
39.Python pass 语句
40.Python 循环嵌套
41.Python 运算符
42.Python log10() 函数
43.Python log() 函数
44.Python floor() 函数
45.Python fabs() 函数
46.Python exp() 函数
47.Python cmp() 函数
48.Python ceil() 函数
49.Python abs() 函数
50.Python Number(数字)
51.Python pow() 函数
52.Python modf() 函数
53.Python min() 函数
54.Python max() 函数
55.Python asin() 函数
56.Python acos() 函数
57.Python uniform() 函数
58.Python shuffle() 函数
59.Python seed() 函数
60.Python random() 函数
61.Python randrange() 函数
62.Python choice() 函数
63.Python sqrt() 函数
64.Python round() 函数
65.Python radians() 函数
66.Python degrees() 函数
67.Python tan() 函数
68.Python sin() 函数
69.Python hypot() 函数
70.Python cos() 函数
71.Python atan2() 函数
72.Python atan() 函数
73.Python 元组
74.Python 列表(List)
75.Python 字符串
76.Python 字典(Dictionary)
77.Python 日期和时间
78.Python 函数
79.Python 模块
80.Python capitalize()方法
81.Python center()方法
82.Python count() 方法
83.Python expandtabs()方法
84.Python endswith()方法
85.Python encode()方法
86.Python decode()方法
87.Python find()方法
88.Python index()方法
89.Python 异常处理
90.Python isspace()方法
91.Python isnumeric()方法
92.Python islower()方法
93.Python isdigit()方法
94.Python isalpha()方法
95.Python isalnum()方法
96.Python isupper()方法
97.Python istitle()方法
98.Python min()方法
99.Python max()方法
100.Python maketrans()方法