Python string formatting when string contains “%s” without escaping

后端 未结 4 1286

When formatting a string, my string may contain a modulo \"%\" that I do not wish to have converted. I can escape the string and change each \"%\"

4条回答
  •  孤城傲影
    2020-12-31 04:08

    You can use regular expressions to replace % by %% where % is not followed by (

    def format_with_dict(str, dictionary):
        str = re.sub(r"%([^\(])", r"%%\1", str)
        str = re.sub(r"%$", r"%%", str)  # There was a % at the end?
        return str % dictionary
    

    This way:

    print format_with_dict('Day old bread, 50% sale %(when)s', {'when': 'today'})
    

    Will output:

    Day old bread, 50% sale today

    This method is useful to avoid "not enough arguments for format string" errors.

提交回复
热议问题