代码之家  ›  专栏  ›  技术社区  ›  uhoh Jacob

评估python格式字符串的期望值数目

  •  0
  • uhoh Jacob  · 技术社区  · 6 年前

    我有一个方法,它接收一个格式字符串和一组由用户提供的值,并使用这些值将输出写入屏幕。

    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'
    

    我想执行一个测试,以发现值的数量与格式“预期”匹配。

    我在下面展示了一个丑陋的测试,如果你不设置,可能会给出错误的结果。 maxcheck 足够高。有没有一种更自然、更不丑陋的方法来确定预期值是多少?

    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
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Peilonrayz    6 年前

    string.Formatter

    >>> import string
    >>> f = string.Formatter()
    >>> l = list(f.parse('Hello, {noun!s: ^4} world{}!'))
    >>> l
    [('Hello, ', 'noun', ' ^4', 's'), (' world', '', '', None), ('!', None, None, None)]
    

    >>> 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)
    

    >>> 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

    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)
    
        2
  •  0
  •   uhoh Jacob    6 年前

    http://www.rexegg.com/regex-cookbook.html

    things = ['pi={:0.2f}, e={:0.4f}', 'pi={:0.2f}, e={q', '{{}',
              '{}wow', 'wow', '{}']      # includes some pathologicals
    
    import re
    
    for thing in things:
        print len(re.findall('{([^{)]*)}', thing)), thing
    

    2 pi={:0.2f}, e={:0.4f}
    1 pi={:0.2f}, e={q
    1 {{}
    1 {}wow
    0 wow
    1 {}
    

        3
  •  -1
  •   Translunar    6 年前
  • 如果您遇到打开格式标记 ( , [, , :
    • 如果级别为0,则递增计数。
    • 增量级别。.
  • 否则,如果遇到结束格式标记 ), , , , . :
    • 如果级别为0,则递减计数。
    • 减量级。
  • 否则,如果您找到其他标记 :、 \t :
    • 什么都不做。
  • 其他(其他字符):