Search code examples
pythonstringcomparison

Why does str.lower() modify modify string comp


I have the following python code snipped and have been getting insane as i don't understand why I'm getting these different results. Can anyone elaborate?

   test = "GTX1050Ti 4GB"

print(test)

if "gtx" and "560" and "ti" in test:
    print("GTX 560 Ti")
else:
    print("nope")
    
print(test.lower())

if "gtx" and "560" and "ti" in test.lower():
    print("GTX 560 Ti")
else:
    print("nope")``` 

Output:

GTX1050Ti 4GB
nope
gtx1050ti 4gb
GTX 560 Ti

Solution

  • You can use all to help ensure the condition is met for all checks

    checks = ['gtx', '560', 'ti']
    if all(check in test for check in checks):
        ....
    
    if all(check in test.lower() for check in checks):
        ....
    

    Then if you need to change what is checked, you only need to do it in once place.