0

Here is my code to solve for this equation manually:

b=2
c=3
sum= [[1, 4 + c, 0], [6, 2 + b + c, b]]
[[1, 7, 0], [6, 7, 2]]

this is the output I get and it works and the type : <class 'list'>

How do I get the same output but as a string? I don't want to change the above list type to string.

b=2
c=3
sum= "[[1, 4 + c, 0], [6, 2 + b + c, b]]"
'[[1, 4 + c, 0], [6, 2 + b + c, b]]'

Why does this not work, it is the right output "type" but the values for b and c don't work.

Thanks for your help.

maymal
  • 3
  • 1

3 Answers3

1

You can use lambda or in other words use function def NOTE: don't use sum as a variable name, because it is a built-in function in python.

b=2
c=3
sum_ = lambda b,c: [[1, 4 + c, 0], [6, 2 + b + c, b]]
sum_(b,c)
[[1, 7, 0], [6, 7, 2]]

Epsi95
  • 8,832
  • 1
  • 16
  • 34
0

This is pretty easy to do. You can use eval() to evaluate python expressions. From the documentation, for eval, the source may be a string representing a Python expression or a code object as returned by compile(). If I understood you correctly, you need to use for strings.

For example,

>>> b=2
>>> c=3
>>> sum= "[[1, 4 + c, 0], [6, 2 + b + c, b]]"
>>> result=eval(sum)
>>> result
[[1, 7, 0], [6, 7, 2]]

If you want to convert it to string, simply do result=str(eval(sum)).

Alex.Kh
  • 572
  • 7
  • 15
0

What about:

sum = f"[[1, {4 + c}, 0], [6, {2 + b + c}, b]]"

Or this:

sum = str([[1, 4 + c, 0], [6, 2 + b + c, b]])

Or even this (not very recommended):

sum = eval("[[1, 4 + c, 0], [6, 2 + b + c, b]]")
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36