Home > Enterprise >  Is there a more Pythonic way to do string case insensitive comparison with None check
Is there a more Pythonic way to do string case insensitive comparison with None check

Time:09-13

@staticmethod
def case_insensitive_comparison(str1, str2):
    if str1 == str2:
        return True
    elif str1 is None or str2 is None:
        return False
    else:
        return str1.upper() == str2.upper()

Is there a better way to do string comparison with none val can be expected?

CodePudding user response:

from typing import Optional

def foo(str1: Optional[str], str2: Optional[str]) -> bool:
    return (str1.upper() if str1 else None) == (str2.upper() if str2 else None)

In this case, str.upper() will always be invoked, which may effect the performance.

  • Related