1

I want to replace any word that ends with "hpp" in the list to instead end with "h". You can see what it is meant to output in the bottom comment. Insted, the string just doesn't get replaced. I am very confused as to why this is and any help is great!

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
newfilenames = []

for i in filenames:
    if i[len(i) - 3:len(i)] == "hpp":
        i.replace("hpp", "h")
        newfilenames.append(i)
    else:
        newfilenames.append(i)

print(newfilenames) 
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
  • do `newfilenames.append(i.replace("hpp", "h"))` or assign *i* with *replace* result, because string cannot be modified, *replace* returns a new string – bruno Mar 07 '21 at 10:49
  • 1
    also: `if i[-3:] == "hpp":` is all thats needed - no need for the `len` shinanigans - you could even do : `i = i.replace(".hpp",".h")` without the test - given your **current** inputs. The dot is important to not replace `'hppopotamus,cpp'` in front. – Patrick Artner Mar 07 '21 at 10:55
  • 1
    Use `str.endswith('hpp')` to pick the files that need the last 3 characters replaced and use a list comprehension: `newfilenames = [f'{s.removesuffix("hpp")}h' if s.endswith('hpp') else s for s in filenames]` – mhawke Mar 07 '21 at 11:06

2 Answers2

2

Because replace() returns a copy of the modified string.

You need to do:

i = i.replace("hpp", "h")

Also, as Patrick comments, it will change the filenames as well if they had hpp in the name.

So, you could replace .hpp with .h:

if i[-3:] == "hpp":
    i.replace(".hpp", ".h")

Also, note that you could do all of this in one line with list comprehension which is preferred in Python over traditional looping:

newfilenames = [filename.replace(".hpp", ".h") for filename in filenames]
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
1

The i.replace() returns the replaced string, but you have to assign it. So:

i = i.replace("hpp", "h")

Now i will contain the replaced string.

Ismail Hafeez
  • 730
  • 3
  • 10