Home > other >  How to remove space after comma in list in python
How to remove space after comma in list in python

Time:03-13

class Solution:
    def buildArray(self, nums):
    
        ans=[]
        for i in range(len(nums)):
            ans.append(nums[nums[i]])
        return ans

    
sol = Solution()  
res = sol.buildArray([0,2,1,5,3,4])
print(res)

output:

[0, 1, 2, 4, 5, 3]

The problem is in the output , iam sturggling to remove space after comma ',' in the list . Can any body help me with this one

CodePudding user response:

You need to turn the list into a string first, which will make that kind of manipulation easier.

Try replacing your last line for this:

res_str = str(res).replace(", ", ',')
print(res_str)

CodePudding user response:

If you have a specific format you want from your list, then I would just create that format instead of trying to modify the list's internal string result.

arr = [0, 1, 2]
res = '[{}]'.format(','.join(map(str, arr)))
print(res)

Should result in: [0,1,2]

EDIT: Fixed a mistake that shouldn't have been.

  • Related