Step 4 Here we use the endswith method. It uses the same syntax as startswith but tests the final characters in a string.
Step 5 If we want to see if something does not match, we can test against the False constant.
phrase = "cat, dog and bird"# Step 1: see if the phrase starts with this string.
# Step 2: a longer prefix.
if phrase.startswith("cat, dog"):
# Step 3: it does not start with this string.
if not phrase.startswith("elephant"):
# Step 4: test the end of the string.
print("Ends with bird")
# Step 5: does not match.
if phrase.endswith("?") == False:
# Does not end in a question mark.
Ends with bird
Some notes, performance. In my performance testing, I have found Python tends to be fastest when the minimal number of statements and method calls are made.
And This means startswith and endswith are a good choice—they can keep program short and clear.
With string-testing methods like startswith and endswith, we can check the beginning and ends of strings. This can avoid complexity in code.