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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 15, 2023 (edit link).