Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string formation using list comprehension

I am trying to form a string using a list.

If the list only has a single element e.g. l = [10] then the string should be 10.

If there are multiple elements e.g. l = [10,20,30] then the string should be 10,20,30.

I tried but it always appends extra , at the end.

"".join("%s," % x for x in l)

This produces 10, and 10,20,30, for the above lists.

like image 305
shrishinde Avatar asked Apr 20 '17 06:04

shrishinde


Video Answer


2 Answers

Just use the following:

','.join(str(n) for n in l)

like image 97
Vadim Landa Avatar answered Sep 19 '22 23:09

Vadim Landa


Here's my solution. I do not know if it satisfies your

str(l)[1:-1]
like image 39
Learning Spirit Avatar answered Sep 19 '22 23:09

Learning Spirit