-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'
6
  • Probably via some code. You have shown none. Commented Jan 12, 2023 at 19:10
  • Don't name a variable input. Doing that replaces the input function. Commented Jan 12, 2023 at 19:12
  • 1
    ', '.join(' '.join(str(x) for x in s) for s in xnput) Commented Jan 12, 2023 at 19:13
  • You can join them together as a list of strings and then you can use join again to turn them into one string. Commented Jan 12, 2023 at 19:13
  • 1
    @Johnny It doesn't replace it per se; it shadows it. Cf. TypeError: 'list' object is not callable. Commented Jan 12, 2023 at 19:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.