0

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?

vitaliis
  • 4,082
  • 5
  • 18
  • 40
SuperDummy
  • 41
  • 1
  • 7

1 Answers1

1

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.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
  • Awesome! This gets the job done, I have other filters that are checking other values so this is good for now thanks! I was wondering, is there a way to limit the amount of values in a path? For example, I want the path to not have more than two values. If path has /yellow/oranges/blue, I want it to get rejected since the limit was only two values? – SuperDummy Feb 03 '22 at 17:09
  • A simple (but somewhat error prone) solution is to just count the slashes: `parsed_url.count('/')`. This will of course treat `'/yellow'` differently from `'/yellow/'`, so perhaps `parsed_url.rstrip('/').count('/')` or even `parsed_url.strip('/').count('/')` is more suitable for you. – jmd_dk Feb 03 '22 at 17:12