oToMaTiX oToMaTiX - 1 year ago 65
Python Question

How to remove part of item and replace list elements in loop?

What am I doing wrong and these two loops are not working?
links is a list.

links = ['newarklongtermparking.com',
'www.airportparkingreservations.com',
'airparkparking.com',
'jfklongtermparking.com',
'book2park.com',
'globalairportparking.com',
'neworleansparking.com',
'parkwayparking.com',
'www.airportparkinginc.com',
'airportparkfly.com',
'unitedairportparking.com',
'www.way.com',
'cheapairportparking.org',
'wallypark.com',
'parkbytheports.com',
'www.cheapparkfly.com']


removing www.



for a in links:
if (a[0] == a[1] == a[2] == 'w'):
a = a[4:]


adding right form of links



for a in links:
a = 'https://www.' + a

Answer Source

What you are doing is modifying the loop variable. This does not affect the list at all. If you want to modify the elements in place, I recommend using enumerate, and then accessing the list items though their indices:

for i, a in enumerate(links):
    prefix = 'https://' if a.startswith('www') else 'https://www.'
    links[i] = prefix + a

After processing, this is what links has:

https://www.newarklongtermparking.com
https://www.airportparkingreservations.com
https://www.airparkparking.com
https://www.jfklongtermparking.com
https://www.book2park.com
https://www.globalairportparking.com
https://www.neworleansparking.com
https://www.parkwayparking.com
https://www.airportparkinginc.com
https://www.airportparkfly.com
https://www.unitedairportparking.com
https://www.way.com
https://www.cheapairportparking.org
https://www.wallypark.com
https://www.parkbytheports.com
https://www.cheapparkfly.com
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download