评估python格式字符串以获取预期的值数 [英] Evaluate python format string for number of values expected
问题描述
我有一种方法,该方法接收用户提供的格式字符串和一组值,并使用这些值将输出写入屏幕.
I have a method that receives a format string and a set of values provided by a user, and uses these to write an output to a screen.
def makestring(fmt, vals):
s = fmt.format(*vals)
return s
fmt_expecting_three = 'a={:0.2f}, b={:0.4f}, c={:0.1f}'
threevalues = [(x+1)/7. for x in range(3)]
makestring(fmt_expecting_three, threevalues)
产生
'a=0.14, b=0.2857, c=0.4'
我想进行测试以发现与期望"格式相匹配的值的数量.
I would like to perform a test to discover the number of values matches what the format is "expecting".
我在下面显示了一个丑陋的测试,如果您没有将maxcheck
设置得足够高,可能会给出错误的结果.有没有更自然,更轻松的方法来找出期望的值?
I show an ugly test below, that can give incorrect results if you don't set maxcheck
high enough. Is there a more natural, less ugly way to find out how many values are expected?
def checkit(fmt, maxcheck=None):
if maxcheck == None:
maxcheck = 10
for i in range(maxcheck-1, 0, -1):
try:
fmt.format(*range(i))
except:
return i+1
fmt_expecting_three = 'a={:0.2f}, b={:0.4f}, c={:0.1f}'
checkit(fmt_expecting_three)
返回
3
推荐答案
我可以通过 string.Formatter
.这样可以确保该字符串实际上是有效的格式字符串,同时为您提供有关该格式的所有信息.
采取:
I'd do this with string.Formatter
. This ensures that the string is actually a valid format string, whilst giving you all the information about the format.
Take:
>>> import string
>>> f = string.Formatter()
>>> l = list(f.parse('Hello, {noun!s: ^4} world{}!'))
>>> l
[('Hello, ', 'noun', ' ^4', 's'), (' world', '', '', None), ('!', None, None, None)]
通过此操作,您可以通过检查第二项是否为None来计算金额.
From this you can count the amount by checking if the second item is None or not.
>>> sum(1 for _, field_name, _, _ in l if field_name is not None)
2
因此您可以使用:
def count_formats(format_string):
f = string.Formatter()
formats = f.parse(format_string)
return sum(1 for _, field_name, _, _ in formats if field_name is not None)
但是,这不适用于嵌套格式.因此,我们需要检查可以嵌套的内容:
This however doesn't work with nested formats. And so we need to check what can be nested:
>>> list(f.parse('{}'))
[('', '', '', None)]
>>> list(f.parse('{:{}}'))
[('', '', '{}', None)]
>>> list(f.parse('{{}:{}}'))
ValueError: Single '}' encountered in format string
>>> list(f.parse('{!{}:{}}'))
ValueError: Single '}' encountered in format string
因此,我们只需要检查格式规范即可查看是否有任何嵌套格式.因此,您可以根据需要将count_formats
更改为嵌套:
And so we only need to check format spec to see if there are any nested formats. And so you can change count_formats
to be nested if you'd like:
def count_formats(format_string):
def nested(s):
for hit in f.parse(s):
yield hit
if hit[2]:
for nested_hit in nested(hit[2]):
yield nested_hit
f = string.Formatter()
formats = nested(format_string)
return sum(1 for _, field_name, _, _ in formats if field_name is not None)
这篇关于评估python格式字符串以获取预期的值数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!