简体   繁体   中英

How to remove space after comma in list in python

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM