pythonstring-formattingargparsepercent-encoding

Python argparse errors with '%' in help string


I have a default value that contains a '%' which I also insert in to the help doc of my argument. E.g.:

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

Argparse errors on parse_args()

[snip]
    args = parser.parse_args()
[snip]"../python2.5/site-packages/argparse.py", line 622, in _expand_help
    return self._get_help_string(action) % params
ValueError: unsupported format character 'O' (0x4f) at index 83

Solution

  • 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.