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
>>> 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}')
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With