Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two conditions for a function

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://')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading