How can I convert a tuple to a float in python?

25,602

struct.unpack always returns a tuple, because you can unpack multiple values, not just one.

A tuple is a sequence, just like a list, or any other kind of sequence. So, you can index it:

>>> a = struct.unpack('f', 'helo')
>>> b = a[0]
>>> b
7.316105495173273e+28

… or use assignment unpacking:

>>> b, = a
>>> b
7.316105495173273e+28

… or loop over it:

>>> for b in a:
...     print(b)
7.316105495173273e+28

And of course you can combine any of those into a single line:

>>> b = struct.unpack('f', 'helo')[0]
>>> b, = struct.unpack('f', 'helo')
>>> c = [b*b for b in struct.unpack('f', 'helo')]

If this isn't obvious to you, you should read Lists, More on Lists, and Tuples and Sequences in the tutorial.

Share:
25,602
user2426316
Author by

user2426316

Updated on December 10, 2020

Comments

  • user2426316
    user2426316 over 3 years

    Say I created a tuple like this using a byte array:

    import struct
    a = struct.unpack('f', 'helo')
    

    How can I now convert a into a float? Any ideas?

  • abarnert
    abarnert over 10 years
    It's already a float; that's guaranteed by using the 'f' format character in struct.unpack. So calling float doesn't do anything useful.
  • abarnert
    abarnert over 10 years
    Well, yes, but a = a[0] also does it. You might as well write a = float(a[int(0)] while you're at it.