I have a list, in which is another list and I want to doc.write(a)
a = [[1, 2, \"hello\"],
[3, 5, \"hi There\"],
[5,7,\"I don\'t know\"]]
There are different legal things you can do, and no way for anyone to say which one is right without knowing which one you want.
First, you can just write the str
or repr
of a
:
>>> a=[[1, 2, "hello"],[3, 5, "hi There"],[5,7,"I don't know"]]
>>> repr(a)
'[[1, 2, \'hello\'], [3, 5, \'hi There\'], [5, 7, "I don\'t know"]]'
Note that this is what print
does (it prints the str
of whatever you give it—although with a list, the str
is identical to the repr
; they're both effectively '[' + ', '.join(map(repr, self)) + ']'
).
Second, you could use a format that's designed for data persistent, like JSON:
>>> json.dumps(a)
'[[1, 2, "hello"], [3, 5, "hi There"], [5, 7, "I don\'t know"]]'
Third, you can join together the repr of each element of a
in some way of your choosing, which is trivial with a map
or a comprehension. For example:
>>> '[' + ', '.join(map(repr, a)) + ']'
'[[1, 2, \'hello\'], [3, 5, \'hi There\'], [5, 7, "I don\'t know"]]'
… or …
>>> 'My stuff includes: ' + ','.join(map(repr, a)) + '\n'
'My stuff includes: [1, 2, \'hello\'],[3, 5, \'hi There\'],[5, 7, "I don\'t know"]\n'
Or you can do the same thing recursively.
Or you can flatten the list (e.g., flatten it one step with itertools.chain
, or recursively with the recipes from the itertools
docs or with the more-itertools
package) and then stringify the pieces however you want and then join them up.
Or you can just write the word LIST
.
All of those are perfectly valid things to pass to write
.