1

input: url = http://127.0.0.1:8000/data/number/

http://127.0.0.1:8000/data/ is consistent for each page number.

output: number

Instead of slicing the url url[-4:-1], Is there any better way to do it?

1
  • Split at /, find index of "data" and take everything from that index on, if you want to allow for multiple things after it. But why do you want to avoid slicing? I think you're going to end up doing it at some phase anyway, I don't see how you can cut anything out from a larger thing without slicing. Commented Jun 4, 2015 at 17:52

2 Answers 2

2

You can use a combination of urlparse and split.

import urlparse
url = "http://127.0.0.1:8000/data/number/"
path = urlparse.urlparse(url).path
val = path.split("/")[2]
print val

This prints:

number

The output of urlparse for the above URL is

ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/data/number/', params='', query='', fragment='')

We are utilizing the path portion of this tuple. We split it on / and take the second index.

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

Comments

2

use urlparse module life would be easier

from urlparse import urlparse
urlparse('http://127.0.0.1:8000/data/number/').path.split('/')[2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.