在某些情况下,你想让你的字符串有点“动态”,即让它们根据变量或表达式的值而改变。例如,您想提示用户输入他们的姓名,并使用他们输入的姓名向他们打印问候语。但是如何将变量嵌入到字符串中呢?如果您以最直观的方式进行操作,您会感到失望:
a = input()
print('Hello, a')
输出将是:
Hello, a
幸运的是,Python 提供了多种方法来按照您想要的方式格式化输出,我们将专注于主要的两个:
- 格式化的字符串文字
str.format()
方法
之前使用了 % 运算符。该内置运算符源自 C 语言,在某些情况下以下列方式使用:
string % value
因此,右侧的变量%
包含在其左侧的字符串中。如果我们想将 11 除以 3,则/
运算符将返回一个带有很多小数位的浮点数。
print(11 / 3) # 3.6666666666666665
使用%
字符,我们可以控制小数位数,例如,将它们的数量减少到 3 或 2:
print('%.3f' % (11/3)) # 3.667
print('%.2f' % (11/3)) # 3.67
对于每个操作,您必须了解大量的说明符、长度修饰符和转换类型。种类繁多的额外运算符导致了一些常见错误。这就是为什么引入了更现代且易于使用的运算符的原因。进步永不止步,你知道的!
格式化你的字符串也让你的代码看起来更易读和更容易编辑。
str. format()
该方法的操作已在其名称中描述:在字符串部分中,我们引入花括号作为格式部分中登记的变量的占位符:
print('Mix {}, {} and a {} to make an ideal omelet.'.format('2 eggs', '30 g of milk', 'pinch of salt'))
表达式按照它们被提及的顺序放置而不是大括号:
Mix 2 eggs, 30 g of milk and a pinch of salt to make an ideal omelet.
如有必要,您可以在一个字符串中多次使用相同的变量。此外,您可以通过引用它们在花括号中的位置来寻址对象(像往常一样,编号从零开始)。注意:您选择的顺序可能非常重要。以下两个代码:
print('{0} in the {1} by Frank Sinatra'.format('Strangers', 'Night'))
和
print('{1} in the {0} by Frank Sinatra'.format('Strangers', 'Night'))
会有不同的输出:
Strangers in the Night by Frank Sinatra
Night in the Strangers by Frank Sinatra
第二个输出听起来很奇怪,不是吗?
如果您在格式部分提到的变量多于需要的变量,则将忽略多余的变量。
我们还可以使用关键字来使此类字符串更具可读性。不要忘记您可以轻松打破界限!例如:
print('The {film} at {theatre} was {adjective}!'.format(film='Lord of the Rings',
adjective='incredible',
theatre='BFI IMAX'))
请注意,如果您使用关键字,也可以根据需要混合顺序。这是格式化的字符串:
The Lord of the Rings at BFI IMAX was incredible!
此外,您可以结合位置参数和关键字参数:
print('The {0} was {adjective}!'.format('Lord of the Rings', adjective='incredible'))
# The Lord of the Rings was incredible!
但是,请注意参数的顺序:
print('The {0} was {adjective}!'.format(adjective='incredible', 'Lord of the Rings'))
# SyntaxError: positional argument follows keyword argument
最后一个代码片段导致SyntaxError
,因为首先要提到位置参数。
格式化的字符串文字
格式化的字符串文字(或者简单地说,f-strings)用于将表达式的值嵌入字符串文字中。这种方式应该是最简单的一种:您只需将f放在字符串之前,并将要嵌入到字符串中的变量放在花括号中。它们也是 Python 中所有字符串格式化方法中的最新功能。
name = 'Elizabeth II'
title = 'Queen of the United Kingdom and the other Commonwealth realms'
reign = 'the longest-lived and longest-reigning British monarch'
f'{name}, the {title}, is {reign}.'
如果你打印这个短字符串,你会看到一个比它在代码中的表示长五倍的输出:
Elizabeth II, the Queen of the United Kingdom and the other Commonwealth realms, is the longest-lived and longest-reigning British monarch.
hundred_percent_number = 1823
needed_percent = 16
needed_percent_number = hundred_percent_number * needed_percent / 100
print(f'{needed_percent}% from {hundred_percent_number} is {needed_percent_number}')
# 16% from 1823 is 291.68
print(f'Rounding {needed_percent_number} to 1 decimal place is {needed_percent_number:.1f}')
# Rounding 291.68 to 1 decimal place is 291.7
您可以在官方文档中阅读更多关于 Python 格式规范迷你语言的信息。
概括
因此,在本主题中,我们学习了几种字符串格式化的方法:使用 % 运算符、str.format() 方法和 f-strings。也许现在你认为这些方法并不重要且被高估了,但在实践中,它们非常有用,让你有机会让你的代码看起来花哨和可读。