问题描述
给出一个文件名列表,我们想将所有扩展名为hpp的文件重命名为扩展名h。为此,我们要生成一个名为newfilenames的新列表,其中包括新文件名。使用列表理解#
filenames = ["program.c","stdio.hpp","sample.hpp","a.out","math.hpp","hpp.out"]
newfilenames = [filename[:len(filename) - 3] + "h" for filename in filenames if filename.endswith("p")]
print(newfilenames)
输出来自["stdio.h","sample.h","math.h"]
应该是["program.c","stdio.h","math.h","hpp.out"]
解决方法
您可以简单地将.hpp
替换为.h
filenames = ["program.c","stdio.hpp","sample.hpp","a.out","math.hpp","hpp.out"]
x=[x.replace(".hpp",".h") for x in filenames]
print (x)
输出:
['program.c','stdio.h','sample.h','a.out','math.h','hpp.out']
,
我认为您需要
filenames = [i[:-3]+"h" if i.split(".")[-1]=="hpp" else i for i in filenames]
print(filenames)