Removing whitespaces from items of the list in Python

Question:

In this Python code

def addToArrayForm(num,k):
    num_string = ""
    answer = []
    for n in num:
        num_string += str(n)
    num_string = int(num_string) + k    # This is an integer
    for i in str(num_string):
        answer.append(int(i))
    print(answer)

addToArrayForm([1,2,0,0], 34)

I get this output => [1, 2, 3, 4]

How can I turn this output [1, 2, 3, 4] to this => [1,2,3,4] (what i wanna do is to remove these spaces between items)???
Please help that’s very important

Asked By: Bazargan_Dev

||

Answers:

You can use replace method.

>>> answer = [1, 2, 3, 4]
>>> print(answer)
[1, 2, 3, 4]
>>> newanser = str(answer).replace(' ', '')
>>> print(newanser)
[1,2,3,4]

Good luck in leetcode 😉

Answered By: Karen Petrosyan
def addToArrayForm(num,k):
    num_string = ""
    answer = []
    for n in num:
        num_string += str(n)
    num_string = int(num_string) + k    # This is an integer
    for i in str(num_string):
        answer.append(int(i))
    return '['+','.join(str(x) for x in answer)+']'  #instead of print use return.

print(addToArrayForm([1,2,0,0],34))
#[1,2,3,4]
Answered By: God Is One
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.