-2

I'm new to Python, may I ask why does my code not work?

Question: square every digit of a number and concatenate them

Input:9119
Output:811181

my code:

def square_digits(num):
    num=str(num)
    newnum=""
    for i in num:
        newnum.append(i**2)
    return int(newnum)

why does it state that:

AttributeError: 'str' object has no attribute 'append'
1
  • 5
    Just for fun a one-liner: return int(''.join((str(int(c)**2) for c in str(num)))) Commented Feb 4, 2022 at 15:03

3 Answers 3

0

You can indeed not use append on a string, but you can add to it. Make sure to manage your varibale types. i is a string and that doesn't support the ** operator. You need to convert i to int, use ** and then convert the result back to str to add it to newnum.

def square_digits(num):
    num=str(num)
    newnum=""
    for i in num:
        newnum += str(int(i)**2)
    return int(newnum)
Sign up to request clarification or add additional context in comments.

Comments

0

You can't use append on variables that are of the str type.
If you want to concatenate strings use join or the += operator. Remember that you have to transform the int into a str using str()

Comments

0

If I well understood, you want to take an integer and return another integer, which is the result of the concatenation of all individual numbers, after squaring each one of them.

The error message you get is because, the append method, in the way that you are trying to use it, it should be a list, but you are applying it to a string (str)

Your code should be like this:

def square_digits(input_int):
    input_str=str(input_int)
    squared_nums=[]
    for each_char in input_str:
        squared_nums.append(int(each_char)**2)
    output = ''.join([str(num) for num in squared_nums])
    return int(output)
square_digits(9119)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.