Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Python
x=10'*'12

I know that if I just remove the quote signs, it'll multiply, but if the * is a string, how do I multiply? This is related to a project of mine, and I'm very new to python.

What I have tried:

I don't even know what to try because it's a python built function
Posted
Updated 5-Apr-22 21:47pm

Do you mean something like:
Python
answer = 0
operator = '*'
operand1 = 10
operand2 = 12
if operator == '*':
    answer = operand1 * operand2
elif operator == '+':
    answer = operand1 + operand2
# etc.
else:
    print('invalid operator')
 
Share this answer
 
v3
You don't, because you're mixing types and assuming that the result will be useful - it won't any more than adding two mobile phone numbers together produces a useful phone number.

What you can do is convert the whole thing to a string and use the Python eval()[^] function to execute it:
Python
x =  str(2) + '*' + str(4)
print (x)
print (eval(x))
 
Share this answer
 
Comments
CPallini 6-Apr-22 2:07am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900