1.Python 使用 % 符号进行字符串格式化的知识点
基本语法
%
符号两边分别是字符串模板和变量(或字典)。- 字符串模板中包含占位符,用
%
后跟一个字符来表示数据类型。
占位符类型
占位符 | 类型 | 示例 | 输出 |
---|---|---|---|
%s | 字符串 | "Hello, %s" % "Alice" | Hello, Alice |
%d | 十进制整数(有符号) | "I am %d years old." % 25 | I am 25 years old. |
%i | 十进制整数 | "Number: %i" % 42 | Number: 42 |
%f | 浮点数 | "Pi is approximately %.2f." % 3.14159 | Pi is approximately 3.14. |
%F | 浮点数(大写) | "Pi is approximately %.2F." % 3.14159 | Pi is approximately 3.14. |
%e | 科学计数法(小写) | "Scientific: %e" % 12345.6789 | Scientific: 1.234568e+04 |
%E | 科学计数法(大写) | "Scientific: %E" % 12345.6789 | Scientific: 1.234568E+04 |
%x | 十六进制(小写) | "Hexadecimal: %x" % 255 | Hexadecimal: ff |
%X | 十六进制(大写) | "Hexadecimal: %X" % 255 | Hexadecimal: FF |
%o | 八进制 | "Octal: %o" % 10 | Octal: 12 |
%c | 单个字符 | "Character: %c" % 'A' | Character: A |
%r | repr() 表示形式 | "Object representation: %r" % [1, 2, 3] | Object representation: [1, 2, 3] |
%% | 百分号 | "Discount: 50%%" | Discount: 50% |
格式控制
可以通过 %[flags][width][.precision][length]specifier
来控制输出格式:
flags
:-
:左对齐。+
:总是显示符号(无论正负)。0
:零填充。- 空格:在正数之前加空格。
#
:为八进制和十六进制添加前缀(0o
或0x
)。
width
: 最小字段宽度。.precision
: 控制小数点后位数或字符串的最大长度。length
(基本未用):h
: 短整数。l
: 长整数。
多参数格式化
可以使用 %
后跟一个元组,元组中的元素依次对应模板中的占位符。
字典格式化
可以使用 %
后跟一个字典,字典的键对应模板中的占位符。
示例
基本使用
age = 25
print("I am %d years old." % age) # 输出: I am 25 years old.
字符串格式化
name = "Alice"
print("Hello, %s!" % name) # 输出: Hello, Alice!
浮点数格式化
pi = 3.1415926
print("Pi is approximately %.2f." % pi) # 输出: Pi is approximately 3.14.
字典格式化
person = {"name": "Bob", "age": 30}
print("%(name)s is %(age)d years old." % person) # 输出: Bob is 30 years old.
多参数格式化
x, y = 10, 20
print("x is %d and y is %d" % (x, y)) # 输出: x is 10 and y is 20
格式控制
number = 123456.789
print("Number: %010d" % number) # 输出: Number: 0000123456
print("Float: %+.2f" % number) # 输出: Float: +123456.79
插入百分号
print("This is 50%%") # 输出: This is 50%
2.Python中str.format()
在Python中,str.format()
方法是一种强大而灵活的字符串格式化方式,可以用来将变量插入到字符串中。
format()方法中<模板字符串>的槽除了包括参数序号,还可以包括格式控制信息。此时,槽的内部样式如下:
{<参数序号>: <格式控制标记>} # 中间使用了一个冒号哦!
其中,<格式控制标记>用来控制参数显示时的格式,包括:
<填充><对齐><宽度><,><.精度><类型>
6 个字段,这些字段都是可选的,可以组合使用,逐一介绍如下
1. <填充>
指<宽度>内除了参数外的字符采用什么方式表示,默认采用空格,可以通过<填充>更换。
示例:
"{:*^10}".format("Test")
将输出 ***Test***
,其中 *
是填充字符,宽度为10,中间对齐。
2. <对齐>
指参数在<宽度>内输出时的对齐方式,分别使用 <
、>
和 ^
三个符号表示左对齐、右对齐和居中对齐。
左对齐示例:
"{:<10}".format("Test")
将输出 Test
(左对齐)。
右对齐示例:
"{:>10}".format("Test")
将输出 Test
(右对齐)。
居中对齐示例:
"{:^10}".format("Test")
将输出 Test
(居中对齐)。
3. <宽度>
指当前槽的设定输出字符宽度,如果该槽对应的 format()
参数长度比 <宽度> 设定值大,则使用参数实际长度。如果该值的实际位数小于指定宽度,则位数将被默认以空格字符补充。
示例:
"{:10}".format("Test")
将输出 Test
,其中宽度为10。
4. 逗号(,)
<格式控制标记> 中逗号(,)用于显示数字的千位分隔符。
示例:
"{:,}".format(1234567)
将输出 1,234,567
。
5. <.精度>
表示两个含义,由小数点(.)开头。对于浮点数,精度表示小数部分输出的有效位数。对于字符串,精度表示输出的最大长度。
浮点数示例:
"{:.2f}".format(3.14159)
将输出 3.14
。
字符串示例:
"{:.5}".format("Hello, World!")
将输出 Hello
,最大长度为5。
6. <类型>
表示输出整数和浮点数类型的格式规则。对于整数类型,输出格式包括6种:
-
二进制方式 (b):
"{:b}".format(10)
将输出
1010
。 -
Unicode 字符 ©:
"{:c}".format(65)
将输出
A
(ASCII码65对应字符A)。 -
十进制方式 (d):
"{:d}".format(255)
将输出
255
。 -
八进制方式 (o):
"{:o}".format(8)
将输出
10
。 -
小写十六进制方式 (x):
"{:x}".format(255)
将输出
ff
。 -
大写十六进制方式 (X):
"{:X}".format(255)
将输出
FF
。
基本使用方法
str.format()
的基本语法是在字符串中使用大括号 {}
作为占位符,并通过 .format()
方法将相应的值插入到占位符中。
示例:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# 输出: My name is Alice and I am 25 years old.
格式化数值
可以指定数值的宽度、精度以及对齐方式等格式选项。
示例:
value = 3.14159
print("The value of PI is approximately {:.2f}".format(value))
# 输出: The value of PI is approximately 3.14
number = 1234
print("Number: {:08d}".format(number))
# 输出: Number: 00001234
使用关键字参数
通过关键字参数,可以显著提升代码的可读性。
示例:
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
# 输出: My name is Bob and I am 30 years old.
多次使用同一变量
可以在同一个字符串中多次使用相同的变量。
示例:
text = "hello"
print("{} {}".format(text, text))
# 输出: hello hello
自定义填充和对齐方式
可以通过指定对齐方式和填充字符来自定义输出格式。
示例:
print("{:<20}".format('left aligned'))
print("{:>20}".format('right aligned'))
print("{:^20}".format('centered'))
print("{:*^20}".format('centered'))
# 输出:
# left aligned
# right aligned
# centered
# *****centered*****
对字典的键进行格式化
可以直接在字符串中访问字典的键。
示例:
person = {'name': 'Charlie', 'age': 35}
print("Name: {person[name]}, Age: {person[age]}".format(person=person))
# 输出: Name: Charlie, Age: 35
嵌套格式化
可以进行更复杂的嵌套格式化操作。
示例:
data = {'first': 'Tom', 'last': 'Hanks'}
print("Actor: {0[first]} {0[last]}".format(data))
# 输出: Actor: Tom Hanks
使用索引
可以通过位置索引来指定格式化参数。
示例:
print("{0} {1}".format('one', 'two'))
print("{1} {0}".format('one', 'two'))
# 输出:
# one two
# two one
实现对对象属性的访问
可以通过格式化字符串访问对象属性。
示例:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('John', 36)
print("Name: {0.name}, Age: {0.age}".format(p))
# 输出: Name: John, Age: 36
处理缺失参数
可以指定默认值来处理缺失的参数。
示例:
print("My name is {name} and my occupation is {job}".format(name="Alice", job="Engineer"))
print("My name is {name} and my occupation is {job}".format(name="Alice"))
# 这行代码会导致KeyError,因为"job"未提供
解决方案:
data = {"name": "Alice"}
print("My name is {name} and my occupation is {job}".format(name=data.get("name", "Unknown"), job=data.get("job", "Unemployed")))
# 输出: My name is Alice and my occupation is Unemployed
字符串的格式对齐方式
<
: 左对齐(默认)>
: 右对齐^
: 居中对齐=
: 指数字符串内补零的方式,常用于数字
示例:
num = 42
print("Binary: {0:b}, Octal: {0:o}, Hexadecimal: {0:x}".format(num))
# 输出: Binary: 101010, Octal: 52, Hexadecimal: 2a