Home > database >  Is there a way to make a string work as a list index?
Is there a way to make a string work as a list index?

Time:04-02

Let's say I've got a string mystr = "mylist[0][1]" and a list called mylist which contains many words. I want to print the second letter of a first word in my list (as my string suggests). How can I do this? When I try to use print(mystr) it obviously prints mylist[0][1] instead of my letter.

CodePudding user response:

use something like this approach:

mystr = "mylist[0][1]"
splited = mystr.split('[')
i = int(splited[1].replace(']', ''))
j = int(splited[2].replace(']', ''))
print(mylist[i][j])

CodePudding user response:

You can use the eval function to interpret a string as code, but I don't recommend it.

print(eval(mystr))

There are many reasons why this is a bad idea:

  1. It is very slow. The Python interpreter has to parse the string, analyze it and interpret it at this point in the program. If it's in a loop, it has to do all the work each time through the loop.

  2. It may be a security risk for code injection. If any part of the string comes from an external input, an attacker could send it some undesirable code that your program would then execute.

CodePudding user response:

Instead of evaluating the string containing an object identifier you can try to access to it via the globals() dictionary. This process is a bit tedious and can be done more rigorously, for example, using a regular expression.

mylist = [[1, 2, 3], [6, 7, 8]]

mystr = "mylist[0][1]"

key, coord1, coord2 = mystr.split('[')
# remove last character, ]
coord1 = int(coord1[:-1])
coord2 = int(coord2[:-1])

l = globals()[key][coord1][coord2]
print(l)
  • Related