String index indices must be integers or slices, not str

this is the new error i am getting:

TypeError: string index indices must be integers or slices, not str at [ServerModule1, line 38](javascript:void(0)) called from [EditComponent, line 31](javascript:void(0))

and this is where is is coming from (lines 30-42):

@anvil.server.callable
def update_item(item_name):
user = anvil.users.get_user()
payments = get_payments_for_user()
if user is None:
return
elif len(payments)==0:
return
elif user != item_name[‘added_by’]:
return
else:
item_name.update(item_name=item_name)
return

Let’s take this situation apart, to see where Python caught the problem.

Counting from 30, the line with the error appears to be:

  elif user != item_name[‘added_by’]:

The only “indexing” (subscripting) occurring here is: item_name[‘added_by’] where ‘added_by’ is the index. The error message calls this a “string index”; that is, item_name contains a value of type str.

Try this expression in any Python interpreter: 'George'['added_by']
You’ll get the same kind of run-time error.

Does this clarify what’s going on?

I suspect that you wanted the index (subscript) on the other object in the test, i.e.,

  elif user[‘added_by’] != item_name:

Does that make more sense?

2 Likes