Recently there's been some discussion around string comprehensions, and I 
wanted to look at a specific variant of the proposal in a bit more detail.
Original thread: 
https://mail.python.org/archives/list/python-ideas@python.org/thread/MVQGP4GGTIWQRJTSY5S6SDYES6JVOOGK/

Let's say i have a matrix of numbers:

matrix = [[randint(7, 50) / randint(1, 3) for _ in range(4)] for _ in range(4)]

I want to format and display each row so that the columns are nicely lined up. 
Maybe also display the sum of the row at the end of each line:

for row in matrix:
    print(''.join(f'{n:>8.3f}' for n in row) + f' | {sum(row):>8.3f}')

This gives me a nicely formatted table. Now with the proposal:

for row in matrix:
    print(f'{n for n in row:>8.3f} | {sum(row):>8.3f}')

The idea is that you would be able to embed a comprehension in f-string 
interpolations, and that the format specifier at the end would be applied to 
all the generated items. This has a few advantages compared to the first 
version. It's a bit shorter and I find it easier to see what kind of shape the 
output will look like. It would also be faster since the interpreter would be 
able to append the formatted numbers directly to the final string. The first 
version needs to create a temporary string object for each number and then feed 
it into the iterator protocol before joining them together.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HSTXKN7OUUR34IXLVMXR65XVPNWPVEL5/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to