为什么Python元组中的空格很重要?

jco*_*ctx 2 python iterable-unpacking

我一直在得到奇怪的结果,我终于注意到我在一个元组中放置空格的习惯导致了这个问题.如果你可以重现这个问题并告诉我它为什么会这样运作,那么你就可以保存我的头发.谢谢!

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
Run Code Online (Sandbox Code Playgroud)

在元组中有空格,答案是错误的.没有,答案是正确的.

Mar*_*ers 12

空间应该没有区别.不同之处在于案例:SWvs Sw.

你不在SW这里检查:

compass in ['S', 'W', 'Sw']] 
Run Code Online (Sandbox Code Playgroud)

也许改成它:

compass.upper() in ['S', 'W', 'SW']] 
Run Code Online (Sandbox Code Playgroud)