Josh Josh - 2 months ago 11
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 (
'PN-{:0>9}'
) 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?

Answer

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
'PN-000000123'
>>> parsed = parse.parse(format_string, pn)
>>> parsed
<Result ('123',) {}>
>>> parsed[0]
'123'
Comments