-2

Hi everyone I'm learning python for a week now and I'm trying to create a simple calculator using eval and I encounter an error. The line below is what I used. value = str(eval(number))

Everytime I enter a number for example 05+05 it gives me an error. Is there a solution so that I can ignore the zeros in front of the number? so that the result would be 5+5?

Jeth
  • 1
  • 1
  • 1
    (1) The simplest thing to do is probably remove leading zeroes with a regular expression, though it will be a bit tricky to get right. (2) Please make sure to read [Why is using 'eval' a bad practice?](https://stackoverflow.com/q/1832940/12299000) - there are other, better ways to make a calculator, which don't create security risks. – kaya3 Feb 21 '23 at 08:31
  • If you are using only integer values you can use the following: value = str(eval(int(number))) – Giordano Feb 21 '23 at 08:31
  • 5
    Please do not get used to `eval`! It is virtually never needed and has serious security implications in real code. Find solutions to write a calculator that does not involve `eval`. Especially if it doesn’t even work for your input, don’t start looking for workarounds to fix problems with it. It also doesn’t teach you programming, you’re just letting Python do the work of evaluating the input instead of doing it yourself. – deceze Feb 21 '23 at 08:34
  • Thank you for your answers. I will try the solutions you give – Jeth Feb 21 '23 at 08:46

1 Answers1

0

you can strip the leading zeros from a string using regex

import re
some_expression = '005+005+05*01-01/02'
filtered_expression = re.sub('(?<!\d)0+(?=\d)','',some_expression)
print(filtered_expression)

this works by selecting all sequences of zeros that have a non-digit character and a digit character after the zeros and removing them.

arrmansa
  • 518
  • 10