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?
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).
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".
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With