Need to Get 4 URLs in Output After Remove Letter S but Get only Last URL

Viewed 35

Below 4 URLs Contain Letter s and We need to remove this Letter and Print the 4 x URLs But The Problem is I got only the last web site not the 4 Sites printed

Note :Language used is Python

file1 = ['https:/www.google.com\n', 'https:/www.yahoo.com\n', 'https:/www.stackoverflow.com\n', 
         'https:/www.pythonhow.com\n']
file1_remove_s = []

for line in file1:
    file1_remove_s = line.replace('s','',1)

print(file1_remove_s)
2 Answers

You are reassigning file1_remove_s from a list object to the modified list element. You want to use append instead

file1 = ['https:/www.google.com\n', 'https:/www.yahoo.com\n', 'https:/www.stackoverflow.com\n', 
         'https:/www.pythonhow.com\n']
file1_remove_s = []

for line in file1:
    file1_remove_s.append(line.replace('s','',1))

print(file1_remove_s)

You are assigning only the last item on the dict by using the = operator. This is actually a perfect place to use a list comprehension, hence your code should look like:

file1 = [file1_remove_s.replace('s','',1) for file1_remove_s in file1]

This will automatically append the formatted text -strings with removed "s" - to a list and by setting the variable name of that list to the name of the initial list, the initial list gets overwritten by the new one which have the proper format of the texts you want.

Related