-2

How to turn a string that contains an array into a normal array without using external modules? For example: “a[0]” into a[0]

edit: I have seen a few complains about the amount of information in this post so I will add some more details about my problem for everyone watching this in future: My intention was to write a string that contains ”array[…]” somewhere in it but I need to execute this array somehow and my best choice was to remove the quotes around it but I don’t want to use eval() because of a few security issues

edit 2: or tell me, how to express an equation in python without instantly solving it and without importing modules

anyone
  • 37
  • 5
  • I not sure but maybe `eval` might help – rv.kvetch Jul 21 '22 at 14:52
  • Does this answer your question? [What does Python's eval() do?](https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do) – n4321d Jul 21 '22 at 16:19
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jul 21 '22 at 16:19
  • `globals()["array"][...]` together with string processing `"array[…]".partition('[')` to separate the identifier from the "positions" – cards Jul 21 '22 at 16:49

1 Answers1

0

one option is to use builtin eval function in python:

a = [  'wowweeeee!' ]

print(eval('a[-1]'))  # wowweeeee!

as @cards mentions in the comments, you can also pass a local dict object to restrict the scope of eval, to help address any security concerns:

try:
    print(eval('a[-1]', {'a': a}))  # wowweeeee!

except NameError as ne:
    print('following variable is missing:', ne)
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53