Home
Map
startswith, endswith ExamplesUse the startswith and endswith methods to test the beginning and end of strings.
Python
This page was last reviewed on Sep 25, 2022.
Startswith, endswith. All things have a start and an end. Often we need to test the starts and ends of strings. We use the startswith and endswith methods.
Some notes. 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.
Substring
Example, startswith. Here we have a string that has many characters in it. We want to see what its prefix may match. We use 3 if-statements.
Next We use startswith on an example string. We use "not startswith" to see if the string does not start with "elephant."
phrase = "cat, dog and bird" # See if the phrase starts with these strings. if phrase.startswith("cat"): print(True) if phrase.startswith("cat, dog"): print(True) # It does not start with this string. if not phrase.startswith("elephant"): print(False)
True True False
Example, endswith. Here we use the endswith method. It uses the same syntax as startswith but tests the final characters in a string. We test a URL's domain with it.
url = "https://www.dotnetperls.com/" # Test the end of the url. if url.endswith("/"): print("Ends with slash") if url.endswith(".com/"): print("Ends with .com/") if url.endswith("?") == False: # Does not end in a question mark. print(False)
Ends with slash Ends with .com/ 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.
So Startswith and endswith are a good choice—they can keep program short and clear.
A summary. With string-testing methods like startswith and endswith, we can check the beginning and ends of strings. This can avoid complexity in code.
C#VB.NETPythonGolangJavaSwiftRust
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 Sep 25, 2022 (edit).
Home
Changes
© 2007-2023 Sam Allen.