我正在使用 python 2.7。我正在尝试匹配两个值
我的代码如下所示
a=field [0] ["inv"] ##This is json calling
aa=purchase [11] [0]
print type(a)
print a
print type(aa)
print aa
if aa==a:
print "same"
else:
print "Not same"
当我执行代码时,我得到以下输出
<type 'str'>
28
<type 'str'>
28
Not same
为什么我得到这个输出。我有匹配的值。但是为什么我得到的输出是 not same。
这背后的问题是什么?
请您参考如下方法:
嗯..有characters that do not show up when printed (whitespace)在你最后一个“正常”字符之后:' ', '\r' '\t' '\n' 和其他人。
检查
if len(aa) != len(a):
print "Invisible characters - length different"
print "'{}' vs '{}'".format(aa,a)
使用 rstrip() (doku-link)删除不需要的空格
if aa.rstrip()==a.rstrip(): # avoid "a" vs "a " comparing to not equal
print "same"
else:
print "Not same"
有帮助。
以下也有帮助:How to debug small programs (#1)
演示:
a = "ff " # 'invisible' difference
aa = "ff"
print type(a)
print a
print type(aa)
print aa
if len(aa) != len(a):
print "Invisible characters - length different"
print "'{}' vs '{}'".format(aa,a)
if aa.rstrip()==a.rstrip():
print "same"
else:
print "Not same"
输出:
<type 'str'>
ff
<type 'str'>
ff
Invisible characters - length different
'ff' vs 'ff '
same
