Like python string endswith() function, in this tutorial, we will introduce how to use python string startswith() function. This function is very useful to help us to filter string.
str.startswith(prefix[, start[, end]])
Parameters
prefix – String or tuple of strings to be checked
start (optional) – Beginning position where prefix is to be checked within the string.
end (optional) – Ending position where prefix is to be checked within the string.
Return Value
True or False
Here are some useful example.
suffix is a string
suffix = 'https' str = 'https://www.tutorialexample.com' starts = str.startswith(suffix) print(starts) #True
startswith() is case sensitive?
suffix = 'HTTPS' str = 'https://www.tutorialexample.com' starts = str.startswith(suffix) print(starts) #False
From the result, we can find string startswith() function is case sensitive.
If start > len(str)?
starts = str.startswith(suffix, len(str)) print(starts) #False
suffix is a tuple
suffix = ('https', 'https://') str = 'https://www.tutorialexample.com' starts = str.startswith(suffix) #1 print(starts) #True pass suffix = ('https', 'ftp://') starts = str.startswith(suffix) #2 print(starts) #True suffix = ('ftp', 'ftp://') starts = str.startswith(suffix) #3 print(starts) #False
From the result, we will find these truth when suffix is a tuple.
- String starts with any element in suffix will return True (#1 and #2).
- Only String starts with none of elements in suffix will return False (#3).