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.

8
  • import parse, format_string='{:1f} {:.2e} {:s} {:d}' pn=format_string.format(1.5,100000,'test',4) parsed=parse.parse(format_string, pn) Does not work Commented Nov 22, 2017 at 22:06
  • Did you download and install the parse module? Commented Nov 22, 2017 at 22:08
  • Yes well of course, in my case type(parsed) is NoneType Commented Nov 22, 2017 at 22:10
  • Have you considered ast.literal_eval? Commented Nov 22, 2017 at 22:17
  • In your format string, replace {:s} with {}. For some reason this works Commented Nov 22, 2017 at 22:22

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@ChrisB You're welcome! If you liked the answer, accept it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.