Python 函数中存在TypeError,但在其他情况下工作正常
下面的代码是“TypeError:字符串索引必须是整数”Python 函数中存在TypeError,但在其他情况下工作正常,python,python-3.x,Python,Python 3.x,下面的代码是“TypeError:字符串索引必须是整数” import json j = { "id": 1000, "name": "John Doe" } def test(j): if j['id']: print("Value present") else: print("No Id found") test(j) 现在运行它: python3 delme.py Value present Traceback
import json
j = {
"id": 1000,
"name": "John Doe"
}
def test(j):
if j['id']:
print("Value present")
else:
print("No Id found")
test(j)
现在运行它:
python3 delme.py
Value present
Traceback (most recent call last):
File "delme.py", line 15, in <module>
test("")
File "delme.py", line 9, in test
if j['id']:
TypeError: string indices must be integers
将j传递给函数时会发生什么变化?而且,J将只有一个“id”键,那么验证它是否存在的最简单方法是什么?。您发布的错误包括test(“”
),它不是您发布的代码
j
是函数的test
参数,因此python正在test
中查找局部变量。如果您试图使用全局测试,那么在没有参数的情况下定义测试
j = {
"id": 1000,
"name": "John Doe"
}
def test(): # note: empty ()
if j['id']:
print("Value present")
else:
print("No Id found")
test() # added a call here
对于将再现错误的代码,全局j
不相关:
def test(j):
if j['id']:
print("Value present")
else:
print("No Id found")
test("") # j will be ""
第二个代码有语法错误。而且,这样的错误只会在处理列表时发生,而您的代码不使用任何列表。请把这个作为一个适当的例子。关于这个错误,我看不出两者之间有什么有效的区别
j
一定在某个地方变成了一个列表。@Carcigenicate我修改了代码。你调用的是test
,而不是字典。@OlivierMelançon我隔离了这段代码。这就是全部代码。@Ethan如果你试着只运行你发布的代码,你会发现它运行得很好。您的错误不是源于此代码。这很清楚,因为它指向第15行,但您的代码段只有14行
def test(j):
if j['id']:
print("Value present")
else:
print("No Id found")
test("") # j will be ""