Python

Timothy Tseng
Timothy Tseng
3,292 Points

How come I can't iterate after coverting an int to str using str() (Solved)

Hi, how come when I try to run the below code I get a TypeError: 'int' object is not iterable

def maximum69Number (self, num: int) -> int:
    string = str(num)
    for digit in len(string):
        if digit ==  '6':
            digit = '9'
            break
    return int(string)

I realized using replace would be easier, but I'm just wondering why my for loop is causing a type error when I'm converting the number to a string.

Timothy Tseng
Timothy Tseng
3,292 Points

Please disregard, I got the loop to work, but I realized that strings are immutable which is why the code is not working, I should have realized sooner as this is something that was covered early on in the Python track!

Chris Freeman
Chris Freeman
Treehouse Moderator 59,232 Points

It's not the immutability of strings that caused it to fail. len(string) returns a single `int value. This single value is assigned to digit which subsequently will never be equivalent to a string value.