在Python中,字符串格式化是一种将变量或表达式嵌入到字符串中的技术。Python提供了多种字符串格式化的方法,包括百分号格式化、str.format()方法和f-string(格式化字符串字面量)。
百分号格式化(%操作符)
这是Python中最早的一种字符串格式化方法。它使用%符号来指示一个占位符,然后将变量插入到这个占位符中。
Python支持格式化字符串的输出。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s
的字符串中。
基本语法
在Python中,字符串格式化使用与C中sprintf函数一样的语法。
百分号格式化字符串的基本语法如下:
%[(name)][flags][width].[precision]typecode
- name:可选参数,当需要格式化的值为字典类型时,用于指定字典的key。
- flags:用于控制对齐和符号显示,例如:
- -:表示左对齐。
- +:表示右对齐,正数前添加正号,负数前添加负号。
- 空格:表示右对齐,正数前添加空格,负数前添加负号。
- 0:表示右对齐,正数前无符号,负数前添加负号,并用0填充空白处。
- width:可选参数,指定格式字符串的占用宽度。
- precision:可选参数,指定数值型数据保留的小数位数。
- typecode:必选参数,指定格式控制符,例如%s用于字符串,%d用于整数,%f用于浮点数等。
python字符串格式化符号:
-
%c
:格式化字符及其ASCII码 -
%s
:格式化字符串 -
%d
:格式化整数 -
%u
:格式化无符号整型 -
%o
:格式化无符号八进制数 -
%x
:格式化无符号十六进制数 -
%X
:格式化无符号十六进制数(大写) -
%f
:格式化浮点数字,可指定小数点后的精度 -
%e
:用科学计数法格式化浮点数 -
%E
:作用同%e,用科学计数法格式化浮点数 -
%g
:%f和%e的简写 -
%G
:%f和%E的简写 -
%p
:用十六进制数格式化变量的地址
格式化操作符辅助指令:
-
*
:定义宽度或者小数点精度 -
-
:用做左对齐 -
+
:在正数前面显示加号( + ) -
<sp>
:在正数前面显示空格 -
#
:在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’) -
0
:显示的数字前面填充’0’而不是默认的空格 -
%
:‘%%‘输出一个单一的’%’ -
(var)
:映射变量(字典参数) -
m.n.
:m是显示的最小总宽度,n是小数点后的位数(如果可用的话)
整数格式化
# 右对齐,宽度为6
>>> "%6d" % 25
' 25'
# 左对齐,宽度为6
>>> "%-6d" % 25
'25 '
>>> "I am %d years old" % 18
'I am 18 years old'
浮点数格式化
>>> "%.2f" % math.pi
'3.14'
# 宽度为6,保留2位小数
>>> "%6.2f" % math.pi
' 3.14'
# 科学计数法
>>> "%e" % math.pi
'3.141593e+00'
字符串格式化
>>> "%s" % "Morris"
'Morris'
# 右对齐,宽度为10
>>> "%10s" % "Morris"
' Morris'
字典格式化
>>> "%(name)s is %(age)d years old." % {"name": "Morris", "age": 18}
'Morris is 18 years old.'
多参数格式化
>>> "x is %d and y is %d" % (18, 20)
'x is 18 and y is 20'
在使用百分号格式化字符串时,要确保占位符(如%s、%d等)与提供的值类型相匹配,否则可能会引发TypeError。
格式控制
# 零填充,宽度为10
>>> "%010d" % math.pi
'0000000003'
# 带符号,保留2位小数
>>> "%+.2f" % math.pi
'+3.14'
插入百分号
>>> "This is %d%%" % 50
'This is 50%'
如果需要在字符串中插入百分号(%),则需要使用两个百分号(%%)来表示。
str.format()方法
str.format()是Python中的一个字符串方法,用于格式化字符串。它允许你构建一个字符串,其中包含“占位符”,这些占位符随后会被format方法中的参数值所替换。这种方法比旧的百分号(%)格式化提供了更多的灵活性和功能。
基本用法
str.format()方法的基本语法如下:
"some_string_with_placeholders".format(value1, value2, ...)
或者,你可以使用关键字参数来指定占位符的名称:
"some_string_with_{placeholder1}_and_{placeholder2}".format(placeholder1=value1, placeholder2=value2)
占位符在字符串中被大括号{}包围。在调用format方法时,你提供的参数会按顺序(或按关键字)替换这些占位符。
使用位置参数
>>> "Hello, {}. You are {} years old.".format("Morris", 18)
'Hello, Morris. You are 18 years old.'
使用关键字参数
>>> "Hello, {name}. You are {age} years old.".format(name="Morris", age=18)
'Hello, Morris. You are 18 years old.'
在占位符中指定顺序
>>> "Hello, {1}. You are {0} years old.".format(18, "Morris")
'Hello, Morris. You are 18 years old.'
访问列表或元组中的元素
>>> person = ["Morris", 18]
>>> "Hello, {}. You are {} years old.".format(*person)
'Hello, Morris. You are 18 years old.'
访问字典中的值
>>> person = {"name": "Morris", "age": 18}
>>> "Hello, {name}. You are {age} years old.".format(**person)
'Hello, Morris. You are 18 years old.'
填充和对齐
# 右对齐,宽度为10
>>> "{:>10}".format(18)
' 18'
>>> "{:10}".format(18)
' 18'
# 左对齐,宽度为10
>>> "{:<10}".format(18)
'18 '
# 居中对齐,宽度为10
>>> "{:^10}".format(18)
' 18 '
指定精度
# 保留两位小数
>>> "{:.2f}".format(math.pi)
'3.14'
>>> "{:6.2f}".format(math.pi)
' 3.14'
使用大括号{}本身
如果你需要在格式化的字符串中包含大括号,你可以通过加倍大括号来实现:
>>> "This is a {{brace}} example.".format(brace="real")
'This is a {brace} example.'
使用format_map()方法
这是str.format()的一个变种,它接受一个字典作为参数。
>>> "Name: {name}, Age: {age}".format_map({"name": "Morris", "age": 18})
'Name: Morris, Age: 18'
实现百分比进度
for i in range(101):
print("\r{:3}%".format(i),end=' ')
time.sleep(0.05)
F-string(格式化字符串字面量)
F-string(格式化字符串字面量)是Python3.6及更高版本中引入的一种字符串格式化方法。它提供了一种简洁、易读且高效的方式来嵌入表达式到字符串字面量中。
基本语法
F-string使用前缀f或F,后跟字符串字面量,其中可以在大括号{}内直接嵌入表达式。例如:
>>> name = "Morris"
>>> age = 18
>>> f"Hello, {name}. You are {age} years old."
'Hello, Morris. You are 18 years old.'
表达式求值
在大括号{}中可以包含任何有效的Python表达式,F-string会在运行时对其进行求值并转换成字符串。例如:
>>> x = 10
>>> y = 20
>>> f"{x} + {y} = {x + y}"
'10 + 20 = 30'
访问变量和属性
你可以直接在大括号中访问变量和对象的属性。例如:
>>> person = {"name": "Morris", "age": 18}
>>> f"My name is {person['name']} and I am {person['age']} years old."
'My name is Morris and I am 18 years old.'
>>> class Person:
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
>>> p = Person("Morris", 18)
>>> f"{p.name} is {p.age} years old."
'Morris is 18 years old.'
调用方法
你可以在大括号中调用对象的方法。例如:
>>> def greet(name):
... return f"Hello, {name}!"
...
>>> f"{greet('Morris')}"
'Hello, Morris!'
格式化数字
你可以使用Python的内置格式化功能来控制数字的显示方式。例如:
>>> f"{math.pi:.2f}"
'3.14'
填充和对齐
你可以使用填充和对齐选项来格式化字符串。例如:
# 右对齐,宽度为10,保留2为小数
>>> f"{math.pi:>10.2f}"
' 3.14'
# 右对齐,宽度为10,保留2为小数,用0填充
>>> f"{math.pi:0>10.2f}"
'0000003.14'
# 居中对齐,宽度为10,保留2为小数
>>> f"{math.pi:^10.2f}"
' 3.14 '
# 左对齐,宽度为10,保留2为小数
>>> f"{math.pi:<10.2f}"
'3.14 '
使用Template类(字符串的string.Template)
string模块提供了一个Template类,它使用美元符号$和花括号{}作为占位符,适用于需要避免变量名冲突的情况。
>>> from string import Template
>>> Template("Name: ${name}, Age: ${age}").substitute(name="Morris", age=18)
'Name: Morris, Age: 18'