In Python what is element of index?

Viewed 58
import socket
try:
    url = input('Enter URL: ')
    host = url.split('/')[2]

    mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysock.connect((host, 80))
    cmd = 'GET ' + host + ' HTTP/1.0\n\n'
    cmd = cmd.encode()
    mysock.send(cmd)

In the above code where it says:

host = url.split('/')[2]

I learnt from a video that to extract the host only it is element of index 2, but what actually is element of index?

2 Answers

Let's see what is happening in the program you attached.

url = input('Enter URL: ')
host = url.split('/')[2]

The first line in this program is gathering the user input. Assume , you gave the following input https://stackoverflow.com/questions/73640369/in-python-what-is-element-of-index , the first part of 2nd line is splitting it using / as the separator.

so url.split('/') returns:

['https:', '', 'stackoverflow.com', 'questions', '73640369', 'in-python-what-is-element-of-index']. 

This is a list and you are trying to get the 3rd index of that list by calling [2] . Note that in Python indices start from 0.

So finally , the variable host would contain 'stackoverflow.com'

An array contains some amount of elements. This example is an array of length 4, which contains the elements 22, 45, 32 and 12. As you can see, it starts counting at 0 and goes up to index - 1:

Index   0   1   2   3
Element 22  45  32  12

The method split returns an array of all the single strings in between your parameter ('/'). Example:

For stackoverflow.com/questions/73640369/in-python-what-is-element-of-index, it would return an array of length 4: ['stackoverflow.com', 'questions', '73640369', 'in-python-what-is-element-of-index'].

Now you access the element at index 2. Because you start counting at 0, it is the 3rd element, in this case 73640369.

So your code doesn't use all of the input, but only what is between the 2nd and 3rd (or end) slash.

Related