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
.
That’s what it was!!
– Joao Peixoto Fernandes
With a for?!?! What do you mean?
– Joao Peixoto Fernandes
>>> list=[1,5,3,6,22,45,63,30,344,22,12,25,10] >>> print(*list, Sep = '-') 1-5-3-6-22-45-63-30-344-22-12-25-10 >>>
– Joao Peixoto Fernandes