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
.