by dec0dedab0de · 8y ago · 0 comments
def example_cheater(color, flavor, age):
template = 'I am {age} years old and I like to wear {color} hats and eat {flavor} icecream'
return template.format(**locals())
Obviously a contrived example, and it can be argued that using locals() is not very pythonic, but I think it makes the code look much nicer. def example_cheater(color, flavor, age):
return f'I am {age} years old and I like to wear {color} hats and eat {flavor} icecream'
Even nicer! >>> pi = 3.14159; two = 2
>>> f"{two:02d} pi is {2*pi:.2f}"
'02 pi is 6.28'It'd be interesting to see if there are any older languages that supported it too.
https://rosettacode.org/wiki/String_interpolation_(included)...
not really: use f-strings when you're passing in variables as-is (or nearly no work), and format() when you need to do work on them before stringifying them; f-strings are naturally (and obviously) more difficult to read when the variables are big, as it obscures the actual text they're being fit into, and where.
The only natural area for preference to apply is whether to do the work before the format() call, name the variables, and change it to an f-string.. or stick with a multi-line format()
I'm not sure theres any real situation where the choice isn't obvious. Maybe if you're doing something like f"list1: {sorted(a)}\nlist2{sorted(b)}", where the work is rather small, but even then f"list1:{}\nlist2:{}".format(sorted(a), sorted(b)) is just as nice, or rather unsatisfying, as the f-string.
Yes it does. You could construct the string using a for-loop. Thank you for proving my point and then down-voting me.
>>> matrix = [(1,2,3),(4,5,6),(7,8,9)]
>>> list(zip(*matrix))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Not as readable as a real maths library, but pretty cool and educational.
Think I came across it in Python in a nut shell, by Alex Martelli
Edit: formatting