Josh Josh - 6 months ago 30
Python Question

Use Python format string in reverse for parsing

I've been using the following python code to format an integer part ID as a formatted part number string:

pn = 'PN-{:0>9}'.format(id)

I would like to know if there is a way to use that same format string (
) in reverse to extract the integer ID from the formatted part number. If that can't be done, is there a way to use a single format string (or regex?) to create and parse?


The parse module "is the opposite of format()".

Example usage:

>>> format = 'PN-{:0>9}'
>>> format_string = 'PN-{:0>9}'
>>> import parse
>>> format_string = 'PN-{:0>9}'
>>> id = 123
>>> pn = format_string.format(id)
>>> pn
>>> parsed = parse.parse(format_string, pn)
>>> parsed
<Result ('123',) {}>
>>> parsed[0]