Home > Blockchain >  Best way to convert multidimensional array to string
Best way to convert multidimensional array to string

Time:12-29

I have a Python multidimensional array:

list = [[0,1,2],[3,4,5],[6,7,8]]

Is there any way to convert it to a string like this one?

# it must keep the brackets
string = "[[0,1,2],[3,4,5],[6,7,8]]"

Of course, I could loop through the array and build my string, but I wanted to know if there's any other better option.

Any help is appreciated.

CodePudding user response:

Simply you can use str method.

l = [[0,1,2],[3,4,5],[6,7,8]]
s = str(s)
print(s) # [[0,1,2],[3,4,5],[6,7,8]]
print(type(s)) # <class 'str'>
print(s[0]) # [

CodePudding user response:

You can convert the string to JSON, to make output compact without spaces there is a line in the docs with details

To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

import json
json.dumps(list, separators=(',', ':'))  # '[[0,1,2],[3,4,5],[6,7,8]]'

CodePudding user response:

This keeps the brackets and converts it to a string.

string = str(list)
  • Related