Search code examples
pythoniterable-unpacking

why would spaces in a Python tuple matter?


I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks!

jcomeau@intrepid:/tmp$ cat haversine.py
#!/usr/bin/python
def dms_to_float(degrees):
 d, m, s, compass = degrees
 d, m, s = int(d), float(m), float(s)
 float_degrees = d + (m / 60) + (s / 3600)
 float_degrees *= [1, -1][compass in ['S', 'W', 'Sw']]
 return float_degrees

jcomeau@intrepid:/tmp$ python
Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) 
[GCC 4.6.1 20110608 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from haversine import *
>>> dms_to_float((111, 41, 0, 'SW'))
111.68333333333334
>>> dms_to_float((111,41,0,'Sw'))
-111.68333333333334

With spaces in the tuple, the answer is wrong. Without, the answer is correct.


Solution

  • The spaces should make no difference. The difference is due to the case: SW vs Sw.

    You don't check for SW here:

    compass in ['S', 'W', 'Sw']] 
    

    Perhaps change it to this:

    compass.upper() in ['S', 'W', 'SW']]