Python 中的字符串格式

已完成

除了转换文本和执行基本操作(例如匹配和搜索)外,在显示信息时必须设置文本的格式。 要使用 Python 显示文本信息,最简单的方法是使用 print() 函数。 你会发现,将变量中的信息和其他数据结构获取到 print() 可使用的字符串中非常重要。

在本单元中,你将了解通过使用 Python 在文本中包含变量值的几个有效方法。

百分号 (%) 格式

字符串中变量的占位符为 %s。 在字符串之后,使用另一个 % 字符,后跟变量名称。 以下示例演示如何使用 % 字符设置格式:

mass_percentage = "1/6"
print("On the Moon, you would weigh about %s of your weight on Earth." % mass_percentage)

输出:On the Moon, you would weigh about 1/6 of your weight on Earth.

使用多个值将更改语法,因为它需要用括号括住传入的变量:

print("""Both sides of the %s get the same amount of sunlight, but only one side is seen from %s because the %s rotates around its own axis when it orbits %s.""" % ("Moon", "Earth", "Moon", "Earth"))

输出:Both sides of the Moon get the same amount of sunlight, but only one side is seen from Earth because the Moon rotates around its own axis when it orbits Earth.

提示

尽管此方法仍然是设置字符串格式的有效方法,但在处理多个变量时,它可能会导致错误并降低代码的清晰性。 本单元中还描述了其他两个格式设置选项,其中任何一个都更适合此目的。

format() 方法

.format() 方法使用大括号 ({}) 作为字符串中的占位符,并使用变量赋值来替换文本。

mass_percentage = "1/6"
print("On the Moon, you would weigh about {} of your weight on Earth.".format(mass_percentage))

输出:On the Moon, you would weigh about 1/6 of your weight on Earth.

不需要给重复的变量赋值多次,使它变得更简洁,因为需要赋值的变量变少了:

mass_percentage = "1/6"
print("""You are lighter on the {0}, because on the {0} you would weigh about {1} of your weight on Earth.""".format("Moon", mass_percentage))

输出:You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

替换使用的是数字,而不是空的大括号。 {0} 表示使用 .format() 的第一个(索引 0)参数,在本例中是 Moon。 对于简单的重复,{0} 效果很好,但它会降低可读性。 为了提高可读性,请在 .format() 中使用关键字参数,并在大括号内引用这些参数:

mass_percentage = "1/6"
print("""You are lighter on the {moon}, because on the {moon} you would weigh about {mass} of your weight on Earth.""".format(moon="Moon", mass=mass_percentage))

输出:You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

关于 f-string

从 Python 版本 3.6 开始,可使用 f-string。 这些字符串看起来像模板,并使用代码中的变量名称。 在上例中使用 f-string 将得到如下结果:

print(f"On the Moon, you would weigh about {mass_percentage} of your weight on Earth.")

输出:On the Moon, you would weigh about 1/6 of your weight on Earth.

变量在大括号中,并且字符串必须使用 f 前缀。

f-string 比任何其他格式设置选项都更简洁。除了它之外,还可用大括号将表达式括起来。 这些表达式可以是函数或直接操作。 例如,如果想要将 1/6 值表示为具有一个小数位的百分比,可直接使用 round() 函数:

print(round(100/6, 1))

输出:16.7

使用 f-string 时,无需提前向变量赋值:

print(f"On the Moon, you would weigh about {round(100/6, 1)}% of your weight on Earth.")

输出:On the Moon, you would weigh about 16.7% of your weight on Earth.

使用表达式不需要函数调用。 任何字符串方法也能做到这一点。 例如,字符串可强制使用特定的大小写来创建标题:

subject = "interesting facts about the moon"
heading = f"{subject.title()}"
print(heading)

输出:Interesting Facts About The Moon