How to print list with comma separators without spaces?

Question:

I need to print list with commas without spaces and enclosed with 2 curly brackets. My code:

x = [1,3,6,7]

x = set(x)

print('{', *x, "}", sep=',')

This prints:

{,1,3,6,7,}

I need it to be like this:

{1,3,6,7}
Asked By: ERJAN

||

Answers:

More symmetric variant:

x = [1, 3, 6, 7]
x = set(x)
print('{{{}}}'.format(','.join(str(i) for i in x)))

Output:

{1,3,6,7}
Answered By: angwrk

Close. You can’t use sep if the brackets are also positional arguments, because it puts the sep between ALL the positional arguments. However, you can use a different print statement.

x = [1,3,6,7]

print('{', end='')
print(*x, sep=',', end='')
print('}')

But the usual way to join things into a string is with the join method of str. But you need strings, so map str:

x = [1,3,6,7]
print('{' + ','.join(map(str, x)) + '}')
Answered By: Kenny Ostrom

You should use .join() method and map() function. Here is the code:

x = [1,3,6,7]

x = set(x)

print('{' + ','.join(map(str, x)) + '}')

You change every element in x to str because .join() do not work with integers.

Output:
{1,3,6,7}

Hope this helps! 🙂

Answered By: FoxFil

Format the string to be printed out first:

x = [1,3,6,7]
x = set(x)
formatted = "{" + ",".join(map(str, x)) + "}"
print(formatted)
Answered By: Roman Pavelka

This can be done with a single f-string as follows:

_list = [1, 3, 6, 7]

print(f"{{{','.join(map(str, _list))}}}")

Output:

{1,3,6,7}

Note:

This also ensures that all elements in the original list are retained and presented in the order in which they exist in the list. Using a set could lose data and/or change order

Answered By: DarkKnight
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.