Search code examples
pythonurlparse

How to check If a value exists in urlparse path


So let's I ask a user for input like this:

url = input('enter URL: ')

parsed_url = urlparse(url).path

>>>>>>>>> /yellow/orange/blue

I only want to check to see if the first value in parsed_url, '/yellow/' exists or not. What would be the best way of going about this?


Solution

  • Assuming that you have something like from urllib.parse import urlparse (meaning that parsed_url is just a str), you can simply do

    if parsed_url.startswith('/yellow/'):
        print('Starts with /yellow/')
    else:
        print('Does not start with /yellow/')
    

    To be clear, str.startswith() will check if the very first thing in the path is '/yellow/'. If you want to allow cases like ' /yellow/...' or :/yellow/... or whatever, the code has to be more involved.