Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing % formatting to f-string

colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
    print(tshirt)

black S
black M
black L
white S
white M
white L

So I am trying to remove those %s %s and instead have a f string formatting. Can someone be kind enough to show how this is done. Thanks

like image 707
Damon Avatar asked Dec 17 '25 12:12

Damon


2 Answers

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> for c in colors:
...    for s in sizes:
...        print(f'{c} {s}')

Another approach is to use itertools.product:

>>> for c, s in itertools.product(colors, sizes):
...     print(f'{c} {s}')   
like image 68
nosklo Avatar answered Dec 19 '25 01:12

nosklo


You can write the variable names in curly brackets ({...}):

for tshirt in (f'{c} {s}' for c in colors for s in sizes):
    print(tshirt)

Although it is a bit strange to use a generator in this case for a for loop: you can unfold this into (two) nested for loops, like in @nosklo's answer (although this of course does not change anything about the usage of the literal string interpolation [PEP-498].

like image 21
Willem Van Onsem Avatar answered Dec 19 '25 02:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!