PythonString methods
str. startswith()
Checks whether a string starts with a given fragment.
- Returns
TrueorFalse.- Changes the original
- No
Example
#Python
urls = ["https://codeworlds.com", "ftp://files.com", "http://example.com"]
for url in urls:
secure = url.startswith("https://")
web = url.startswith(("http://", "https://"))
print(url, secure, web)Resultsaved result, you can check it
https://codeworlds.com True True
ftp://files.com False False
http://example.com False True
Definition and usage
#The startswith() method returns True if the string starts with the given prefix. It is clearer and safer than comparing the slice string[:n].
As the argument you can pass a tuple of prefixes, and the method checks whether the string starts with any of them: url.startswith(("http://", "https://")).
The comparison is case-sensitive. If it should not be, convert the string to lowercase first.
Syntax
#Syntax
string.startswith(prefix, start=0, end=len(string))Parameters
#prefix
str or tuple of strings
A prefix, or several prefixes.start
int, optional
The position to start checking from.
Good practices
#- For several prefixes, pass a tuple, not a list. A list raises an error.
- After checking a prefix, you can remove it with
removeprefix().
Related entries
#Spotted a mistake or missing an example? Write to us.