Check if string starts with any of two (sub) strings

Question:

I’m trying to pass a number of options for a bolean function and I wrote it like this:

s = 'https://www.youtube.com/watch?v=nVNG8jjZN7k'
s.startswith('http://') or s.startswith('https://')

But I was wondering if there’s a more efficient way to write it,
something like:

s.startswith('http://' or 'https://')
Asked By: Noft

||

Answers:

str.startswith can take a tuple of strings as an argument. It will return true if the string starts with any of them.

s.startswith(('http://', 'https://'))

However, it might be simpler to use a regular expression to capture the idea of the s being optional:

bool(re.match('https?://', s))

If the match succeeds, you get back a truthy re.Match object. If the match fails, you get back the falsy value None.

Answered By: chepner

you can use urllib.parse.urlparse

from urllib.parse import urlparse


url = 'https://www.youtube.com/watch?v=nVNG8jjZN7k'

if urlparse(url).scheme in ("http", "https"):
   ...

More useful methods in the docs https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse

Answered By: Axeltherabbit
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.