如何在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 42printing 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-align2. - 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 titlesRoger Federer
Roger Federer
Roger Federer
Roger F
带有新样式的字符串和整数插值:{}
如果您使用的是Python 3.5或更高版本,则可以使用以下部分 的“新样式”格式。
“ {}”格式的语法为format_string.format(data)。
请记住,函数的参数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开始。Roger Federer是网球界的传奇人物,我个人希望将他表示为#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
这种样式的噪音较小,因为它消除了字典中的一些引号和格式说明符中的许多字符,但是很难引起人们的注意。
以上是 如何在Python中将数据值内插到字符串中? 的全部内容, 来源链接: utcz.com/z/330838.html