Search code examples
pythonmathcharacter-encodingspecial-charactersidentifier

How to convert Multiplication sign into Asterisk sign in python?


I have a math solver python program but it can't read "×" sign, so It can not solve the equation. Is there any way to convert "×" into "*"?

Python shell:

>>> 3 × 5
`SyntaxError: invalid character in identifier
>>> 3 * 5
15
>>> 

screenshot

Update: I tried this too, but did not work.

 if (parser.getPayload().lower()[:6]=="solve:"):
                    if ("×" in parser.getPayload().lower()):
                        str.replace("×","*")
                        parser.sendGroupMessage(parser.getTargetID(), str(ast.literal_eval(parser.getPayload()[7:])))

Solution

  • Let's go over your code line by line.

    if (parser.getPayload().lower()[:6]=="solve:"):
    

    Fine I guess, don't know your protocol but makes sense this way.

                        if ("×" in parser.getPayload().lower()):
    

    Converting to lower case should not be needed. If it were, caching that might be useful. I also wonder whether you need that check, or whether you might as well do the replacement unconditionally, since that makes the code easier and should't be much of a performance problem. It might even help performance since you avoid scanning for the first × twice.

                            str.replace("×","*")
    

    str.replace is a method of the class str, not a function in some module called str. You need to call the replace method on your payload. So either use something like parser.setPayload(parser.getPayload().replace("×","*")) or store the payload in a local variable which you can modify.

                            parser.sendGroupMessage(parser.getTargetID(), str(ast.literal_eval(parser.getPayload()[7:])))
    

    Are you sure you only want to do this in the case there is a × in the input? Anyway, read the docs for ast.literal_eval: it will not evaluate operators. So this is not what you need. If you need to evaluate operators, you may call eval, but if you do, you must sanitize your input first to ensure it doesn't do anything evil.

    I'd do something like this:

    sanitizeRegexp = re.compile(r"\A[0-9+\-*/ ]*\Z") # only allow these
    payload = parser.getPayload()
    if payload.lower()[:6] == "solve:":
        payload = payload[7:] # strip command
        payload = payload.replace("×", "*")
        if sanitizeRegexp.match(payload):
            result = str(eval(payload))
        else:
            result = "Invalid input: " + payload
        parser.sendGroupMessage(parser.getTargetID(), result)