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.
Here we have a string
that has many characters in it. We want to see what prefixes and suffixes may match. We use several if
-statements.
startswith
on an example string
. We see that the string
begins with the letters "cat."string
. We can use any length of string
as an argument to startswith
.startswith
" to see if the string
does not start with "elephant."endswith
method. It uses the same syntax as startswith
but tests the final characters in a string
.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
In my performance testing, I have found Python tends to be fastest when the minimal number of statements and method calls are made.
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.