2014-04-01 14 views
2

我試圖建立一個函數來驗證一個字符串不包含大括號({}),除了那些可能用於一個級別的格式。也就是說,我希望允許大括號在對字符串的.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方法格式化,以儘量使相關的大括號消失。

+0

XY問題? http://www.perlmonks.org/?node_id=542341 –

+0

@MartijnPieters:問題是這樣的:無論你如何格式化{{word}}或'{{{word}}}',在一次調用'.format'後會留下大括號。 – Bach

+0

@ColonelPanic:這主要是爲了純粹的好奇心問的。 – Bach

回答

6

使用string.Formatter() 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 
+1

我正在研究類似的方法,但我認爲它必須更聰明一些。考慮一下''{{word}}「案例。 [有趣的是:我們的代碼之間的唯一區別是,我保留了OP的「單詞」作爲參數名稱,並且將'return True'放在'try'中。否則相同..] – DSM

+0

@DSM:確實;調整爲允許更嚴格的限制。 –

+0

@MartijnPieters:你的速度是壓倒性的。 – Bach

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 
相關問題