将多维数组转换为字符串的最佳方法

Best way to convert multidimensional array to string

我有一个Python多维数组:

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

有没有办法把它转换成这样的字符串?

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

当然,我可以遍历数组并构建我的字符串,但我想知道是否还有其他更好的选择。

感谢任何帮助。

您可以将字符串转换为 JSON,为了使输出紧凑而没有空格,有一个 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]]'

这会保留括号并将其转换为字符串。

string = str(list)

只需使用str方法即可。

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]) # [