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

假装没事ソ 提交于 2019-11-30 08:20:14

You could (and should) use the new string .format() method (if you have Python 2.6 or higher) instead:

"Day old bread, 50% sale {0}".format("today")

The manual can be found here.

The docs also say that the old % formatting will eventually be removed from the language, although that will surely take some time. The new formatting methods are way more powerful, so that's a Good Thing.

Not really - escaping your % signs is the price you pay for using string formatting. You could use string concatenation instead: 'Day old bread, 50% sale ' + whichday if that helps...

Escaping a '%' as '%%' is not a workaround. If you use String formatting that is the way to represent a '%' sign. If you don't want that, you can always do something like:

print "Day old bread, 50% sale " + "today"

e.g. not using formatting.

Please note that when using string concatenation, be sure that the variable is a string (and not e.g. None) or use str(varName). Otherwise you get something like 'Can't concatenate str and NoneType'.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!