python-3.xfileindexingextendcoursera-api

Extend list in a specific index


Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
new_filename=[]
new_list=[]
final_file=[]
for element in filenames:
    if element.endswith("p"):
        new_filename.append(element)
for element1 in new_filename:
    new_list.append(element1.split("pp")[0])
for element3 in filenames:
    if not element3.endswith("p"):
        final_file.append(element3)
final_file.extend(new_list)
print(final_file)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

Is there any way to extend new_list to final_file at the index[1]?

Is there any simpler solutions?


Solution

  • a simpler way to do it:

    filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
    final_file=[]
    for file in filenames:
        if file.endswith(".hpp"):
            final_file.append(file.replace('.hpp','.h'))
        else:
            final_file.append(file)
    

    replace() will just replace a sub-string with another