String startswith, endswith Examples
This page was last reviewed on Jun 15, 2023.
Dot Net Perls
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.
Example. 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.
Step 1 We use startswith on an example string. We see that the string begins with the letters "cat."
Step 2 We test a longer prefix to the string. We can use any length of string as an argument to startswith.
Step 3 We use "not startswith" to see if the string does not start with "elephant."
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 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).
© 2007-2024 Sam Allen.