0

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]))
Palak Soni
  • 53
  • 1
  • 11
  • Does this answer your question? [Understanding repr( ) function in Python](https://stackoverflow.com/questions/7784148/understanding-repr-function-in-python) – FObersteiner Feb 16 '20 at 11:03
  • Note#1: `split()` returns a list of substrings; `f_extns[-1]` just gives you the last element of that list. Note#2: using `repr()` in the print call gives you e.g. a nice `The extension of the file is : 'txt'` for a txt file; without the `repr()`, that would just be `The extension of the file is : txt`. – FObersteiner Feb 16 '20 at 11:08
  • 1
    Note#3: actually, I think it could be more readable to use a simple f-string here, e.g. `print(f"The extension of the file is '{f_extns[-1]}'")` – FObersteiner Feb 16 '20 at 11:12
  • @palak soni can you please check if your query has been answered. If yes, then please accept this answer. – Rahul Goel Feb 16 '20 at 19:03

1 Answers1

2

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)
michael_heath
  • 5,262
  • 2
  • 12
  • 22
Rahul Goel
  • 842
  • 1
  • 8
  • 14