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
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 😉
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]
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
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 😉
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]