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?

2
  • If you always want to ignore the first match you could write something like: fields = request['url'].split('/')[1:] Commented Jun 8, 2020 at 10:54
  • 1
    this answer helps stackoverflow.com/a/34844548/9050514 Commented Jun 8, 2020 at 10:57

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

what if the string has more than one empty string
In that case I would use a the built in filter function
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 😎

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.