Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?

前端 未结 9 1412
迷失自我
迷失自我 2020-12-20 11:19

For instance, say I wanted a function to escape a string for use in HTML (as in Django\'s escape filter):

    def escape(string):
        \"\"\"
        Retu         


        
9条回答
  •  情话喂你
    2020-12-20 11:38

    You can use reduce:

    reduce(lambda s,r: s.replace(*r),
           [('&', '&'),
            ('<', '<'),
            ('>', '>'),
            ("'", '''),
            ('"', '"')],
           string)
    

提交回复
热议问题