Given a set of file names
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
I want to change the files ending with ".hpp" to end with ".h", like this:
['program.c', 'stdio.h', 'sample.h', 'a.out', 'math.h', 'hpp.out']
using list comprehension I'm able to select and change my targets,
newfilenames = [x[:-3]+"h" for x in filenames if x[-3:] == "hpp"]
but this ignores all others and outputs only:
['stdio.h', 'sample.h', 'math.h']
Is there a way to use reduce my code below to a one-liner using ternary operations on list comprehension
newfilenames = []
for x in filenames:
newfilenames.append(x[:-3]+"h") if x[-3:] == 'hpp' else newfilenames.append(x)
print(newfilenames)