Reputation: 23
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?
Upvotes: 2
Views: 3718
Reputation: 50190
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.
Upvotes: 1
Reputation: 7631
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)
Upvotes: 1
Reputation: 85442
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))
Upvotes: 1
Reputation: 174624
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)
Upvotes: 0