Replace function error!

Screen Link:

https://app.dataquest.io/m/331/python-data-analysis-basics/3/converting-ages-to-decades

My Code:


x = [44,59,66,77,111,22]


for ages in x:
    ages = str(ages)
    if ages != 'Unknown':
        ages = ages.replace(ages[-1],'0s')
        print (ages)

What I expected to happen:

40s
50s
60s
70s
110s
20s

What actually happened:

0s0s
50s
0s0s
0s0s
0s0s0s
0s0s

I was trying to do this exercise using replace function but for some reason it does not work where the ending values are duplicates. Can someone explain me the process behind this. Thanks

You don’t need to replace it.

ages = ages.replace(ages[-1],‘0s’)

instead use

    ages= ages[:-1]
    ages= ages + "0s"
1 Like

replace() works by replacing one string with another. It’s not dependent on the location of the string. It just replaces the string directly if it finds a match.

So, for 44, you have ages.replace("4",'0s') and it will replace any 4 that it finds in ages.

You need to account for that in your code. You are already on the right track by using indexing for this. But replace() is not really required here.

1 Like

Thanks for the clarification. Didn’t knew that replace function works that way. I thought it replaces a particular position that we pin point but instead it replaces all the positions with an exact match in a string. :heart:

1 Like