简体   繁体   中英

python string to number with format string

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?

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))

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 (eg 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)

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)

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. Eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM