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}
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}
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)) + '}')
Format the string to be printed out first:
x = [1,3,6,7]
x = set(x)
formatted = "{" + ",".join(map(str, x)) + "}"
print(formatted)
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
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}
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}
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)) + '}')
Format the string to be printed out first:
x = [1,3,6,7]
x = set(x)
formatted = "{" + ",".join(map(str, x)) + "}"
print(formatted)
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