Python startswith, endswith ExamplesUse the startswith and endswith methods to test the beginning and end of strings.
dot net perls
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.
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."
Python program that uses startswith
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.
Python program that uses endswith
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. 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.
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.
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.