If there are multiple APIs available to perform similar action, choose the most specialised and efficient one. This helps make your code more readable and easier to understand.
1def compare_strings_noncompliant():
2 samplestring1 = "samplestring1"
3 samplestring2 = "samplestring"
4 # Noncompliant: uses find() but ignores the returned position
5 # when nonnegative.
6 if samplestring1.find(samplestring2) != -1:
7 print("String match found.")
8 else:
9 print("String match not found.")
1def compare_strings_compliant():
2 samplestring1 = "samplestring1"
3 samplestring2 = "samplestring"
4 # Compliant: uses the in operator to test for presence.
5 if samplestring1 in samplestring2:
6 print("String match found.")
7 else:
8 print("String match not found.")