List separated by "-"

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 this list on a single line and separated by "-".

I've tried it 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'
    
asked by anonymous 29.04.2018 / 17:51

2 answers

5

Do you want to break down the items and save in a variable in what way? Another identical list? It does not make sense to do this because the result will be identical.

One way to do what you want is:

print(*lista, sep = '-')

So the list goes in as follow-up items instead of the object as a whole, and has the argument sep to set the tab.

It is also possible to do with for .

    
29.04.2018 / 18:00
3

Just for another alternative, you can use join string to achieve your goal. This allows you to join multiple elements by 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 begins with the separator calling the function join :

'-'.join(

Next comes the elements that will keep the separator around, which would be lista . In this case, since the list has numeric values, they have to be converted to text with the function map :

map(str, lista)

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

See this example in Ideone

Of course you can do everything in one statement if you want:

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

By using list comprehensions you can also convert slightly different way:

>>> 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 this latter case it is more evident that it makes str(num) for each number that is in the list, thus generating a new list only with the numbers in string , being that used in join .

    
30.04.2018 / 01:49