1

i have this array

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

i would like to convert it in to a string like this

1,2,3,4,5,6,7,8,9

i have tried doing the below code but it didnt do what i wanted to

 A = str(A).strip('[]')

output i get for this is

1, 2, 3], [4, 5, 6], [7, 8, 9

note: i would like to do this without any external libraries

so basically converting 2d array into strings separated by commas

o3203823
  • 63
  • 1
  • 11
  • 2
    First [flatten the list](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists), then convert the numbers to string, and finally [use `str.join`](https://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings). In this case, it would be: `", ".join([str(item) for sublist in A for item in sublist])`. I think this should be a dupe of the two posts I linked. – pault Dec 13 '18 at 22:25
  • Possible duplicate of [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Gigazelle Dec 14 '18 at 00:20

1 Answers1

0

The better way to do this is @pault's suggestion (see comments). Flatten your list, and join with a comma:

>>> ', '.join([str(i) for x in A for i in x])
'1, 2, 3, 4, 5, 6, 7, 8, 9'

But to address the issue with your code, str.strip only removes the trailing and leading characters, which is why you end up with your brackets still in the middle. You could chain two replaces together instead (but joining a flattened list is better):

>>> str(A).replace('[','').replace(']','')
'1, 2, 3, 4, 5, 6, 7, 8, 9'
sacuL
  • 49,704
  • 8
  • 81
  • 106