Can Anyone explain why we are taking [-1] and the use of repr function over here. Can't we use any other function ?
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
Can Anyone explain why we are taking [-1] and the use of repr function over here. Can't we use any other function ?
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
In this example, that you have shared :
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
Use of repr()
is explained here.
split()
method will split the string on the occurrence of .
and you will be getting an list type of object as a result.
You can check that by type(f_extns)
which is <class 'list'>
.
As extensions are after dot for retrieving last element of the list by using negative index f_extns[-1]
or you can use f_extns[len(f_extns) - 1]
.
Another way you can achieve this by :
import os
filename = input("Input the Filename: ") # demo.py
name, ext = os.path.splitext(filename) # name = "demo", ext = ".py"
ext_with_dot = ext[1:]
print ("The extension of the file is : " + ext)