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:
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.