如何在 Python 中将数据值插入字符串?


我们可以使用各种格式将数据值插入字符串。我们可以用它来调试代码、生成报表、表单和其他输出。在本主题中,我们将了解三种字符串格式化方法以及如何将数据值插入字符串。

Python 有三种格式化字符串的方法

  • % - 旧式方法(Python 2 和 3 中都支持)

  • () - 新式方法(Python 2.6 及以上版本)

  • {} - f-字符串(Python 3.6 及以上版本)

旧式方法:%

旧式字符串格式化的形式为 format_string % data。格式字符串不过是插值序列。

语法
描述
%s
字符串
%d
十进制
%x
十六进制整数
%o
八进制整数
%f
十进制浮点数
%e
指数浮点数
%g
十进制或指数浮点数
%%
字面量 %


# printing integer with % style type.
print('output \nprinting a number in string format %s' % 42)
print('printing a number in string decimal %d' % 42)
print('printing a number in string hexa-int %x' % 42)
print('printing a number in string exponential-float %g' % 42)

输出

printing a number in string format 42
printing a number in string decimal 42
printing a number in string hexa-int 2a
printing a number in string exponential-float 42

使用旧格式 % 进行字符串和整数插值

字符串中的 %s 表示插入一个字符串。字符串中 % 出现的次数需要与 % 后面字符串之后的的数据项数量相匹配。

单个数据项紧随其后的那个最终 %。多个数据必须分组到一个元组中,请参见下面的示例。

您还可以将格式字符串中 % 和类型说明符之间的其他值添加到指定最小和最大宽度、对齐方式以及填充字符。

1. + means right-align
2. - means left-align
3. . means separate minwidth and maxchars.
4. minwidth means mimimu field width to use
5. maxchars means how many characters/digits to print from the data value


player = 'Roger Federer'
country = 'Legend'
titles = 20

# note please try this only on Python 2. If you are running on Python3 output for below commands will vary a lot.

print('Output \n*** Tennis player %s From %s had won %d titles ' %(player,country,titles))
print('%s' % player) # print player
print('%5s' % player) # print firstname of player
print('%-7s' % player) # Last Name of player
print('%5.7s' % player) # Last Name of player with 5 leading spaces

输出

*** Tennis player Roger Federer From Legend had won 20 titles
Roger Federer
Roger Federer
Roger Federer
Roger F

使用新式方法:{} 进行字符串和整数插值

如果您使用的是 Python 3.5 或更高版本,则可以使用下面部分中描述的“新式”格式化。

“{}” 格式化的语法为 format_string.format(data)。

请记住,format() 函数的参数需要按照格式字符串中 {} 占位符的顺序排列。有时为了提高可读性,您可以将字典或命名参数传递给 format。

player = 'Roger Federer'
player = 'Roger_Federer'
country = 'Legend'
titles = 20

print('Output \n{}'.format(player))
print(' *** Tennis player {} From {} had won {} titles '.format(player,country,titles))

# positonal arguments
print(' *** Tennis player {1} From {2} had won {0} titles '.format(titles,player,country))

# named arguments
print(' *** Tennis player {player} From {country} had won {titles} titles '.format(player = 'Roger Federer',country = 'Legend',titles = 20))

# Dictionary arguments
print(' *** Tennis player {player} From {country} had won {titles} titles '.format(player = 'Roger Federer',country = 'Legend',titles = 20))

# alignment left '<' (default)
print(' *** Tennis player {} From {:<5s} had won {:<5d} titles '.format(player,country,titles))

# alignment left '<' (default)
print(' *** Tennis player {} From {:<5s} had won {:<5d} titles '.format(player,country,titles))

# alignment center '^'
print(' *** Tennis player {} From {:^10s} had won {:^10d} titles '.format(player,country,titles))

# alignment right '>'
print(' *** Tennis player {} From {:>10s} had won {:>10d} titles '.format(player,country,titles))


输出

Roger_Federer
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger Federer From Legend had won 20 titles
*** Tennis player Roger Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles

使用最新式方法:f-字符串 进行字符串和整数插值

f-字符串出现在 Python 3.6 中,并很快成为推荐的字符串格式化方式。我个人使用这种格式。要创建 f-字符串

1. 在起始/初始引号之前使用字母 f/F。
2. 在花括号 ({}) 内包含变量名或表达式以将其值插入字符串。

player = 'Roger_Federer'
country = 'Legend'
titles = 20

print(f"Output \n *** Tennis player {player} From {country} had won {titles} titles ")
print(f" *** I hope {player} wins another {titles - 10} titles ")
print(f" {'*' * 3} Tennis player {player.upper()} From {country:.^10} had won {titles} titles")

输出

*** Tennis player Roger_Federer From Legend had won 20 titles
*** I hope Roger_Federer wins another 10 titles
*** Tennis player ROGER_FEDERER From ..Legend.. had won 20 titles

现在我们已经介绍了基础知识,让我们进入一些实际问题,以及我为什么建议开始使用格式化字符串。

titles = [
('federer', 20),
('nadal', 20),
('djokovic', 17),
]
print('Output\n')
for i, (player, titles) in enumerate(titles):
print('#%d: %-10s = %d' % (
i + 1,
player.title(),
round(titles)))

输出

#0: federer = 20
#1: nadal = 20
#2: djokovic = 17

显然,在向高层发送报告时,不希望看到从 0 开始的索引,他们希望从 1 开始。罗杰·费德勒作为网球传奇人物,我个人希望将他表示为 #1 而不是 #0。

现在要进行更改,请查看在使用旧格式时代码的可读性是如何变化的。

titles = [
('federer', 20),
('nadal', 20),
('djokovic', 17),
]
print('Output\n')
for i, (player, titles) in enumerate(titles):
print('#%d: %-10s = %d' % (
i + 1,
player.title(),
round(titles)))

输出

#1: Federer = 20
#2: Nadal = 20
#3: Djokovic = 17

总之,我提供了一个示例来说明为什么 f-字符串更容易管理。

old_school_formatting = (
' Tennis Legeng is %(player)s, '
' %(player)s had won %(titles)s titles, '
'and he is from the country %(country)s.')
old_formatted = old_school_formatting % {
'player': 'Roger Federer',
'titles': 20,
'country': 'Swiss',
}
print('Output\n' + old_formatted)

输出

Tennis Legeng is Roger Federer, Roger Federer had won 20 titles, and he is from the country Swiss.


new_formatting = (
' Tennis Legeng is {player}, '
' {player} had won {titles} titles, '
'and he is from the country {country}')
new_formatted = new_formatting.format(
player= 'Roger Federer',
titles= 20,
country= 'Swiss',
)
print('Output\n' + new_formatted)

输出

Tennis Legeng is Roger Federer, Roger Federer had won 20 titles, and he is from the country Swiss

这种风格稍微不太冗余,因为它消除了字典中的一些引号以及格式说明符中相当多的字符,但它并不引人注目。

更新于: 2020-11-10

191 次查看

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告