How to escape $ on Python string Template class?

后端 未结 3 1215
无人共我
无人共我 2021-01-01 17:56

Introduction

The string module has a Template class, that lets you make substitutions in a string using a mapping object, for instance:

>>>          


        
3条回答
  •  余生分开走
    2021-01-01 18:36

    This is a Quick Fix (Using recursion):

    def check_substitution(tem, m):
        try:
            string.Template(tem).substitute(m)
        except KeyError:
            return False
        except ValueError:
            return check_substitution(tem.replace('$ ', '$'), m) #strip spaces after $
        return True
    

    I Know its take a longer time if there is more than One Space between $ and var , so you may improve it by using Regular Expression.

    EDIT

    escaping $ into $$ makes more sense [ Thanks @Pedro ] so you can catch ValueError by this statement:

    return check_substitution(tem.replace('$ ', '$$ '), m) #escaping $ by $$
    

提交回复
热议问题