How to merge 2d array into string in python

Viewed 126

I have tried this solution but the problem I am facing is that when I want to convert

[[65, 'D', 'M', 'A', 'H'], [65, 'S', 'I', 'N']] 

to string using the method above , what i get is

'65DMAH65SIN'

but what I want is

'65DMAH 65SIN'

i.e after every array ends, it gives me space. I am thinking of logics for this but not working.

2 Answers

I would use following comprehension for that task:

a = [[65, 'D', 'M', 'A', 'H'], [65, 'S', 'I', 'N']]
s = ' '.join(''.join(map(str,i)) for i in a)
print(s)

Output:

65DMAH 65SIN

For every sublist I map it, so every element of sublist become str, then I join elements of every sublist without separator (empty str), which then I join using space.

Your problem answer is:

def solution(List):
    result = ''
    for i in range(len(string)):
        for j in string[i]:
            result+=str(j)
        result+=' '
    return result
Related