How to concatenate items from a python list?

Asked

Viewed 7,309 times

1

Let’s say I got the result of a list:

['_', '_', '_', '_', '_', '_', '_']

how can I turn her into this?:

['_ _ _ _ _ _ _']

Or even in a variable with the above value

  • can use for x in list: ; result += x . If you want to write a full answer.

  • It would help a lot, I’m already trying with the for but did not succeed..

  • List items will be strings ?

  • Yes, I need to concatenate the items and add a mirror between each one equal in the example

  • So Danilo, the answer below, from Max solves your problem. But if you have to have a formatting between the list items the answer would be another.

  • It looks a lot like that, but instead of ''.join() use ' '.join. If you have lists inside non-standard lists, you can turn them into a single list (thus) and then give a .join()

Show 1 more comment

2 answers

7


You can use the join and then turn its return into a single element array.

separator = ' '
array = ['_', '_', '_', '_', '_', '_', '_']
result = [separator.join(array)]
print(result)

The print will be:

['_ _ _ _ _ _ _']

1

You can use this also to get fewer lines.

array = ['_', '_', '_', '_']
result = [' '.join(array)]
print(result)

Upshot:

['_ _ _ _']
  • 1

    If it’s just to get fewer lines, it could be print([' '.join(['_', '_', '_', '_'])]) :D By the way, I didn’t really understand the reason for the answer, and the only thing that changed was not using a variable as a separator.

  • I’m new to the area haha, your way is better

  • 1

    Don’t look on the bad side. I only really commented because I didn’t understand the reason of the answer, since it is the same solution, without benefits or harm. We always respond when there is a difference worth quoting. Anyway, welcome to the community. I recommend doing the [tour] to interact.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.