Since you need to replace one extension with another you should work with string slicing.
Note that the extensions you need to replace have 4 characters who are; .hpp
. this way you need to go through the list that contains all the strings, checking if any of them - which I will call it i - has the length equal to .hpp
, that is, if the respective index string is sliced -4 until the end forms the extension .hpp
. In other words...
i[-4:] == '.hpp'
If any of these extensions are .hpp
, we should replace them with .h
. What we achieve with a concatenation between the string part WITHOUT the extension with the new extension .h
, that is to say:
i[:-4] + '.h'
Using this logic together with List Comprehension, we can implement the following code:
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames = [i[:-4] + '.h' if i[-4:] == '.hpp' else i for i in filenames]
print(newfilenames)
In this way, we obtain as output, the following result:
['program.c', 'stdio.h', 'sample.h', 'a.out', 'math.h', 'hpp.out']
Another agile way to resolve this issue is by calling the function replace. This way the code would be:
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames = [i.replace('.hpp', '.h') for i in filenames]
print(newfilenames)
In this code, the for block goes through the list filename, replacing all substrings .hpp for .h.