2

I would like to have inverse function of string formatting with Python. It is like strptime in time module.

 str = '%d %f %d'%( 1 , 5.09 , 77)

str is '1 5.090000 77'.

The funcution would be

ret_tuple = SOMETHING( "1 5.090000 77" , "%d %f %d")

return value is (1,5.09,77).

Does anybody know such a function, or shall I implement by myself?

2
  • How do you get 5.09 from 5.090000? Commented Nov 11, 2015 at 6:47
  • @BurhanKhalid Try float('5.090000').
    – Remi Guan
    Commented Nov 11, 2015 at 7:00

4 Answers 4

1

The inverse of number formatting is just float():

x = float("5.09000")

I would recommend just converting everything to float, not a mix of floats and ints-- a mix means that your code never knows which data type is at hand. Anyway you can drop all-zero decimal parts on printing.

line = "1 5.090000 77"
numbers = [ float(n) for n in line.split() ]

But if you really want your data to be a mix of floats and ints, you can do it like this:

numbers = [ (float(n) if "." in n else int(n)) for n in line.split() ]

If you need to specify in advance which format will be used for each number (regardless of what the input looks like), then just use @BurhanKhalid's answer. E.g., if you want the first number to become a float even if it is given as "3"; but note that if an int is expected and you see "2.0", you'll get an error with that approach.

1
  • if I have "%d+%d=%d" or something replaced by %f or even %s , how could I do it so?
    – deuterium
    Commented Jul 31, 2021 at 16:52
1

This would work:

def convert(string, types):
    return tuple(typ(entry) for typ, entry in zip(types, string.split()))

convert("1 5.090000 77", (int, float, int))
1

I assume you want it to work for a general format string, which isn't necessarily separated by spaces. You can use the python equivalent of C's sscanf. Download the scanf python module from here and install it (e.g. using pip -e [extracted path]/scanf).

In [1]: import scanf

In [2]: scanf.sscanf("1 5.090000 77" , "%d %f %d")
Out[2]: (1, 5.09, 77)
0

I don't know why you would want this, but as a very simple case:

fmap = {'%d': int, '%f': float}

def silly_convert(number, formats):
   return tuple(fmap.get(i, str)(x)
                for i,x in zip(formats.split(' '), number.split(' ')))

>>> silly_convert("1 5.090000 77" , "%d %f %d")
(1, 5.09, 77)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.