0

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)

1 Answers1

0

you can structure your list comprehension with an if / else condition as follows:

newfilenames = [x[:-3]+"h" if x[-3:] == "hpp" else x for x in filenames]

this will allow the list comprehension to modify "hpp" strings to "h", but also include your other elements that aren't intended to change.

Eric
  • 504
  • 4
  • 4