Startswith, endswith. All Python strings have a start and an end. Often we need to test the starts and ends of strings. We use the startswith and endswith methods.
We can take a substring and compare that to a string—this can do the same thing as startswith or endswith. But with specialized methods, our code is clearer and likely faster.
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.
if phrase.startswith("cat"):
print(True)
# Step 2: a longer prefix.
if phrase.startswith("cat, dog"):
print(True)
# Step 3: it does not start with this string.
if not phrase.startswith("elephant"):
print(False)
# Step 4: test the end of the string.
if phrase.endswith("bird"):
print("Ends with bird")
# Step 5: does not match.
if phrase.endswith("?") == False:
# Does not end in a question mark.
print(False)True
True
False
Ends with bird
False
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 15, 2023 (edit link).