Python argparse errors with '%' in help string

Another way to include defaults is with a %(default)s in the help line.

p=argparse.ArgumentParser()
p.add_argument('--foo', default="5% foo", help="Foo amount. Default: %(default)s")
p.print_help()

which produces

usage: ipython [-h] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   Foo amount. Default: 5% foo

From the argparse documentation:

The help strings can include various format specifiers to avoid repetition of things like the program name or the argument default. The available specifiers include the program name, %(prog)s and most keyword arguments to add_argument(), e.g. %(default)s, %(type)s, etc.:


If you do not have a default value and just want to have a percentage sign in the help message, add a another % to escape it:

import argparse
p=argparse.ArgumentParser()
p.add_argument('--foo', help="Foo is always 100%%!")
p.print_help()

Which gives you:

usage: [-h] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   Foo is always 100%!

I had tried a traditional escape character, which did not work. Then I found a comment about using a '%' as an escape character and this worked. E.g.:

default = "5% foo"
foo_group.add_argument(
    "--foo",
    default=default,
    help="Foo amount. Default: %s" % default.replace(r"%", r"%%")),
)
args = parser.parse_args()

I'm glad I don't need to replace all '%' with '[percent sign]'. Hah.