0

I receive three strings from the user.

P=...
Q=...
R=...

They can include, x, y, z and operators +, - , *, ^, /

I want to form a list, F=[P, Q, R] For example, if user had given P = x, Q = y, R = z, the corresponding list would be F=[x,y,z]. I would receive them as strings

P="x"
Q="y"
R="z"

Now how to create F as mentioned before and not as a list of strings?

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
  • So you don't want them as strings, that's fine. But do the names `x`/`y`/`z` already defined and refer to some objects in the current namespace? – heemayl Nov 05 '19 at 12:25
  • It is not clear what you are asking. `x`, `y` and `z` would be the names of variables that are already defined? I don't understand your question, but maybe you want to have a look at sympy: https://scipy-lectures.org/packages/sympy.html – Jonathan Scholbach Nov 05 '19 at 12:25
  • you want to add the three strings to a list but not as a list of strings? – luigigi Nov 05 '19 at 12:25
  • Can you read your question again? I dont understand anything. Read this please https://stackoverflow.com/help/how-to-ask – Wonka Nov 05 '19 at 12:26

1 Answers1

1
P, Q, R = "x", "y", "z"
x, y, z = 1, 2, 3
F=[eval(P), eval(Q), eval(R)] #evals to [1, 2, 3]

works if you already have variables defined with the correct names.

However note that, as mentioned in comments and here for example, this is bad practice:

  1. There is almost always a better way to do it
  2. Very dangerous and insecure
  3. Makes debugging difficult
  4. Slow

There are safer alternatives as @anentropic suggests, like ast.literal_eval.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29