Search code examples
pythonsubtractionstring-length

why is the length subtraction returning an error?


For len(x) - len(y) below, I seem to be getting an error saying the minus sign(-) is 'an invalid character in identifier'- any idea why?

def mxdiflg(a1, a2):
    for x in a1:
        print(len(x))
    for y in a2:
        print(len(y))
        return (max(abs(len(x) − len(y))))

print(mxdiflg(s1,s2))

Solution

  • You are using m-dash instead of minus sign hyphen. Replace the line by

    return (max(abs(len(x) - len(y))))
    

    Python as well as most programming languages uses hyphen "-" for subtraction operation. It can be found to the right of '0' key on most keyboards.

    Em dash "–" is a symbol that is meant to be longer than hyphen, but looks almost the same as hyphen in code because monospaced font is commonly used to display the code.

    There also exist symbol minus sign "−", but it is not a valid operator in Python. It is commonly used to nicely display negative numbers in user interface, but not in the code.

    Monospaced font (as seen in the code):

    "-" hyphen
    "–" em dash
    "−" minus
    

    Proportional font (regular text):

    "-" hyphen
    "–" em dash
    "−" minus