0

Consider a simple string like '1.5 1e+05 test 4'. The format used in Python 2.7 to generate that string is '%f %e %s %i'. I want to retrieve a list of the form [1.5,100000,'test',4] from my input string knowing the string formatter. How can I do that (Python 2.7 or Python 3)?

Thanks a lot,

Ch.

ChrisB
  • 123
  • 1
  • 3
  • 13

1 Answers1

1

Use the parse module. This module can do 'reverse formatting'. Example:

from parse import parse

format_str = '{:1f} {:.2e} {} {:d}' 
data = [1.5, 100000, 'test', 4]
data_str = format_str.format(*data)
print(data_str) # Output: 1.500000 1.00e+05 test 4
parsed = parse(format_str, data_str)
print(parsed) # Output: <Result (1.5, 100000.0, 'test', 4) {}>
a, b, c, d = parsed # Whatever
Jerfov2
  • 5,264
  • 5
  • 30
  • 52