Search code examples
pythonstringcomparison

String comparison if-statement used by Python


I understand(I've read about "The comparison uses lexicographical ordering") how "String comparison technique used by Python" works, but in line if email.rfind('.') > email.find('@') + 1: Im not able to figure out how and why it works. Dot . is 46, and @ is 64.

print("a " + str(ord("a")))
print("b " + str(ord("b")))
print("c " + str(ord("c")))
print(". " + str(ord(".")))
print("@ " + str(ord("@")))

print('aab' < 'aac')
print()


def check_email(email):
    if " " not in email and "@" in email:
        if email.rfind('.') > email.find('@') + 1:
            return True
    return False


print(check_email("[email protected]"))
print(check_email("[email protected]"))
print(check_email("mailfff@xuss"))

OUTPUT:

a 97
b 98
c 99
. 46
@ 64
True

True
True
False

Solution

  • Because rfind returns the position of character in the string not the ascii value like ord

    >>> email = "[email protected]"
    >>> email.rfind('.')
    9
    >>> email.rfind('@')
    7
    

    so if email.rfind('.') > email.rfind('@') returns True