List separated by "-"

Asked

Viewed 377 times

2

The theme is as follows:

I have a list[1,5,3,6,22,45,63,30,344,22,12,25,10]

And I wanted to print the elements of that list in one line and separated by "-".

I’ve tried that way

    lista=[1,5,3,6,22,45,63,30,344,22,12,25,10]
>>> newlista = lista.split('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'

2 answers

5


Do you want to dismember the items and store them in a variable in what way? Another identical list? It makes no sense to do this because the result will be identical.

One of the ways to do what you want is to:

print(*lista, sep = '-')

I put in the Github for future reference.

Thus the list enters as items followed instead of the object as a whole, and has the argument sep to set the tab.

It is also possible to do with a for.

4

Just to get another alternative, you can use the function join of string to achieve its goal. It allows you to join several elements forming a new string with a separator defined by si:

>>> lista_em_texto = '-'.join(map(str, lista))
>>> print(lista_em_texto)
1-5-3-6-22-45-63-30-344-22-12-25-10

First start with the separator calling the function join:

'-'.join(

Then comes the elements that will get the separator around, which would be the lista. In this case as the list has numerical values, these had to be converted into text with the function map:

map(str, lista)

This map maps each of the numbers to text using str in each of them.

See this example in Ideone

Naturally you can do everything in one instruction if you want:

print('-'.join(map(str, lista)))

Using list comprehensions can also convert slightly differently:

>>> lista_em_texto = '-'.join([str(num) for num in lista])
>>> print(lista_em_texto)
1-5-3-6-22-45-63-30-344-22-12-25-10

In the latter case it is more evident that it does str(num) for each number that is in the list, thus generating a new list only with the numbers in string, the latter being used in join.

Browser other questions tagged

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