在 python 中打印文件扩展名

Printing the extension of a file name in python

谁能解释一下为什么我们要取 [-1] 以及 repr 函数的使用。 我们不能使用任何其他功能吗?

filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

在此示例中,您已共享:

filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

解释 repr() 的使用 here

split() 方法将在出现 . 时拆分字符串,结果您将获得一个列表类型的对象。 您可以通过 type(f_extns) 进行检查,即 <class 'list'>.

因为扩展名在 之后,可以使用 negative index f_extns[-1] 检索列表的最后一个元素,或者您可以使用 f_extns[len(f_extns) - 1].

另一种实现此目的的方法:

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)