C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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)
Output
True
True
False
Python program that uses endswith
url = "https://www.dotnetCodex.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)
Output
Ends with slash
Ends with .com/
False
So: Startswith and endswith are a good choice. They can keep program short and clear.