Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Given the list of filenames, we want to rename all files with extension hpp to the extension h. To do this, we would like to generate the new list named newfilenames, consisting of a new filename. Using list comprehension#

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)

output came ["stdio.h", "sample.h", "math.h"] Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

1 Answer

0 votes
by (36.8k points)

You need to use:

filenames = [i[:-3]+"h" if i.split(".")[-1]=="hpp" else i for i in filenames]

print(filenames)

Improve your knowledge in data science from scratch using Data science online courses 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...