Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The indexing ([x:-1]) is returning everything but what I need

link = "https://www.imdb.com/title/tt123456/"
ID = (link.split("/")[4])[2:-1]
print(ID)

This seems to be printing the following:

12345

Should the following code print instead:

123456

I had previously replaced this code with:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID = (movie.split("/")[4])[2:len(movie.split("/")[4])]

which did work fine but I am curious as to why this code wouldn’t work.
TIA!

>Solution :

If you go through each line, you’ll see where it goes wrong.

>>> link.split("/")
['https:', '', 'www.imdb.com', 'title', 'tt123456', '']
>>> link.split("/")[4]
'tt123456'
>>> link.split("/")[4][2:-1]
'12345'

When slicing, the last number is exclusive, meaning that you want all numbers from index 2 up to the last but not including the last. Instead, change the slice to this:

>>> link.split("/")[4][2:]
'123456'

By omitting the end index, you tell Python that you want a slice from index 2 up til (and including) the last.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading