验证字符串是否不包含除用于格式化的方括号以外的花括号

2024-04-25 13:15:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个函数来验证字符串是否不包含花括号({}),而不是那些可以用于一级格式设置的括号。也就是说,我希望允许在对字符串的.format方法进行一次调用之后,可能消失的花括号。你知道吗

例如,如果此验证函数被调用no_curly_braces,则应返回以下结果:

>>> no_curly_brackets("word")
True
>>> no_curly_brackets("{word")  # False, as .format raises ValueError
False
>>> no_curly_brackets("{}word")  # True, as .format(3) returns '3word'
True
>>> no_curly_brackets("{word}")  # True, as .format(word=3) returns '3'
True
>>> no_curly_brackets("{{word}}")  # False, as .format returns '{word}'
False
>>> no_curly_brackets("{{{word}}}")  # False, as .format(word='a') returns '{a}'
False
>>> no_curly_brackets("{word}{{}}")  # False, as .format(word=3) returns '3{}'
False

等等。你知道吗

我的问题是像"{" in str这样的尝试会失败(因为模板可能包含这些花括号),我不能在不知道应该为.format方法提供什么的情况下格式化,以便尝试使相关的花括号消失。你知道吗


Tags: 方法函数no字符串falsetrueformatas
2条回答

以下是基于我上述评论的答案:

def no_curly_brackets(fmt):
  n = 0
  for c in fmt:
    if c == '{':
      n=n+1
    elif c == '}':
      n=n-1
    if n < 0 or n > 1:
      return False
  return (n == 0)

一些示例结果:

word True
{word False
{}word True
{word} True
{{word}} False
{{{word}}} False
{word}{{}} False

使用^{} class

from string import Formatter

def no_curly_brackets(fmt):
    try:
        parsed = Formatter().parse(fmt)
        return not any('{' in lt or '}' in lt for lt, _, _, _ in parsed)
    except ValueError:
        return False

基本上,任何可以解析为格式并且在解析的文本中不包含花括号的内容都是True。你知道吗

这与您的所有测试用例相匹配:

>>> for test in tests:
...     print test, no_curly_brackets(test)
... 
word True
{word False
{}word True
{word} True
{{word}} False
{{{word}}} False
{word}{{}} False

加上我自己的一些:

>>> no_curly_brackets('word}}')
False
>>> no_curly_brackets('{{word')
False
>>> no_curly_brackets('word{{}}')
False

相关问题 更多 >