1

I'm using split to parse http requests and came across something that I do not like but don't know a better way.

Imagine I have this GET : /url/hi

I'm splitting the url simply like so:

fields = request['url'].split('/')

It's simple, it works but it also makes the contents of the list have the first position as an empty string. I know this is expected behavior.

The question is: Can I change the calling of split to contemplate such thing or do I just live with it?

walkman
  • 478
  • 1
  • 8
  • 21

2 Answers2

1

If you just always want to remove the first entry to the list you could just do this:

fields = request['url'].split('/')[1:]

If you just want to remove any empty strings from the list you can use instead follow your initial call with this:

fields.remove('')

Hope it helps!

Fredrik Nilsson
  • 549
  • 4
  • 13
0

Ok, If you sure your string start with '/' you can ignore first character like this:

url = request['url']
fields = url[1:].split('/')   #[1: to end]

If your not sure, simple check first:

url = request['url']
if url.startswith('/'):
    url = url[1:]
fields = url.split('/')

Happy coding

Peyman Majidi
  • 1,777
  • 2
  • 18
  • 31