-1

How would I go about converting a list of list of integers to a single string in Python. The numbers in the sublist would be separated by a space and the sublists by a comma.

Like this:

input = [[1,2,3],[4,5,6],[7,8,9]]
output = '1 2 3, 4 5 6, 7 8 9'
N.n
  • 1
  • Probably via some code. You have shown none. – roganjosh Jan 12 '23 at 19:10
  • Don't name a variable `input`. Doing that replaces the `input` function. – 001 Jan 12 '23 at 19:12
  • 1
    `', '.join(' '.join(str(x) for x in s) for s in xnput)` – 001 Jan 12 '23 at 19:13
  • You can [join them together as a list of strings](https://stackoverflow.com/questions/22105741/converting-a-list-of-lists-into-a-list-of-strings-python) and then you can use join again to turn them into one string. – Alias Cartellano Jan 12 '23 at 19:13
  • 1
    @Johnny It doesn't replace it per se; it [shadows](https://en.wikipedia.org/wiki/Variable_shadowing) it. Cf. [TypeError: 'list' object is not callable](/q/31087111/4518341). – wjandrea Jan 12 '23 at 19:21
  • Welcome to Stack Overflow! Please take the [tour]. In the future, please try solving the problem yourself first. There are multiple aspects to this task, and it's not clear which ones you need help with exactly, but thankfully we have existing questions that cover all of them, so I've closed your post accordingly. See [ask]. – wjandrea Jan 12 '23 at 19:28

1 Answers1

0

you can use the join function in python to achieve the result

print(", ".join([ " ".join([str(a) for a in x]) for x in input]))

PS:

if you want to concatenate the list, there is a chain functionality in itertools that can help you achieve this

from itertools import chain

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

print(list(chain(*input)))

although you should try to do it with simple loops first as well for your practice and building logic

ashish singh
  • 6,526
  • 2
  • 15
  • 35
  • 1
    This outputs `[1, 2, 3, 4, 5, 6, 7, 8, 9]` which is different than the OP's desired output of `1 2 3, 4 5 6, 7 8 9` – 001 Jan 12 '23 at 19:18