Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Python format string in reverse for parsing

Tags:

python

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?

like image 436
Josh Avatar asked May 19 '12 07:05

Josh


People also ask

How do you reverse a string in Python?

Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

How do I reverse a string format?

string formatString = "My name is {0}. I have {1} cow(s)."; string s = String. Format(formatString, "strager", 2); // Call the magic method... ICollection<string> parts = String. ReverseFormat(formatString, s); // parts now contains "strager" and "2".


1 Answers

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

Example usage:

>>> 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' 
like image 81
Brian Dorsey Avatar answered Sep 27 '22 21:09

Brian Dorsey