7

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.

1
  • Then throw away the last character of that string with [:-1], i.e. "".join("%s," % x for x in l)[:-1] Commented Apr 20, 2017 at 6:55

2 Answers 2

11

Just use the following:

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

Sign up to request clarification or add additional context in comments.

1 Comment

To people reading this and using a different separator character than ,, you can replace that with any other string (ex. '--'.join(...)) or even an empty string (ex. ''.join(..)).
1

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

str(l)[1:-1]

1 Comment

This will work with some change str(l)[1:-1].replace(" ", "")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.