I'm trying to print a list with {} curly braces.
For example:
the_list = [1, 2, 3]
and I want to print the list as
{1, 2, 3}
How can I do that? Thanks!
I'm trying to print a list with {} curly braces.
For example:
the_list = [1, 2, 3]
and I want to print the list as
{1, 2, 3}
How can I do that? Thanks!
You can do this like this:
print('{' + ', '.join([str(x) for x in the_list]) + '}')
', '.join joins each element with a ', '
[str(x) for x in the_list] makes each number a string so it can be joined as above.
print(str(list).replace('[','{').replace(']','}'))
this converts the list to a string and replaces "[]" with "{}"
In Python 2, try:
my_list = [1, 2, 3]
print '{{{}}}'.format(', '.join(map(str, my_list)))
In Python 3, try:
my_list = [1, 2, 3]
print(f'{{{", ".join(map(str, my_list))}}}')
Whenever you're looking to get one of your objects in a specific format, check .format() https://docs.python.org/2/library/stdtypes.html#str.format
It uses {} as placeholders (can be made more complex, that's just a simple example). And to escape { and }, just double it, like so: "{{ }}". This latter string, after formatting, will become "{ }".
In Python 3, you now have f-strings https://www.python.org/dev/peps/pep-0498/
They work the same as ''.format() but they are more readable: ''.format() => f''.
Then, you want all your elements (in the list) to be transformed into strings -> map(str, my_list).
And then, you want to glue each of these elements with ", ". In Python, there is a function that does just that: https://docs.python.org/2/library/stdtypes.html#str.join
', '.join(my_iterable) will do it.
And last but not least, do not name your list list. Otherwise, you'll rewrite the builtin list and you won't be able to use lists anymore.
Check this answer for a good list of these keywords: https://stackoverflow.com/a/22864250/8933502
If you want to get hacky:
>>> l = [1, 2, 3]
>>> '{%s}' % str(l).strip('[]')
>>> {1, 2, 3}
There are two approaches to answering this question:
A. Modify str(alist) by replacing [] with {}. @Garret modified the str result calling str.replace twice. Another approach is to use str.translate to make both changes at once. A third, and the fastest I found, is to slice off [ and ], keep the content, and add on { and }.
B. Calculate what str(alist)[1:-1] calculates but in Python code and embed the result in {...}. With CPython, the multiple replacements proposed for building the content string are much slower:
import timeit
expressions = ( # Orderd by timing results, fastest first.
"'{' + str(alist)[1:-1] + '}'",
"str(alist).replace('[','{').replace(']','}')",
"str(alist).translate(table)",
"'{' + ', '.join(map(str, alist)) + '}'",
"'{{{}}}'.format(', '.join(map(str, alist)))",
"'{' + ', '.join(str(c) for c in alist) + '}'",
)
alist = [1,2,3]
table = str.maketrans('[]', '{}')
for exp in expressions:
print(eval(exp)) # Visually verify that exp works correctly.
alist = [1]*100 # The number can be varied.
n =1000
for exp in expressions:
print(timeit.timeit(exp, number=n, globals=globals()))
Results with 64-bit 3.7.0b2 on Windows 10:
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
0.009153687000000021
0.009371952999999988
0.009818325999999988
0.018995990000000018
0.019342450999999983
0.028495214999999963
The relative results are about the same for 1000 and 10000.
EDIT: @Mike Müller independently posted the slice expression, embedded in the following two expressions, with essentially the same timings as the top expression above.
"f'{{{str(alist)[1:-1]}}}'",
"'{%s}' % str(alist)[1:-1]",
('{}'.format(the_list)).replace('[','{').replace(']','}')
Result
{1, 2, 3}
Using Python 3.6 f-strings:
>>> lst = [1, 2, 3]
>>> print(f'{{{str(lst)[1:-1]}}}')
{1, 2, 3}
or with format for Python < 3.6:
>>> print('{{{}}}'.format(str(lst)[1:-1]))
{1, 2, 3}
or with the old, but not deprecated %:
>>> print('{%s}' % str(lst)[1:-1])
{1, 2, 3}