4 ms·
Despite being so cool, it's also a very under utilized feature, as it inherits all the formatting capabilities of format(). With format(), and hence with f-str
by sametmax 7y ago
Despite being so cool, it's also a very under utilized feature, as it inherits all the formatting capabilities of format().
With format(), and hence with f-string you can:
# Replace datetime.stftime()
>>> f"{datetime.now():%m/%d/%y}"
'05/15/19'
# Show numbers in another base
>>> f"{878:b}"
'1101101110'
>>> f"{878:x}"
'36e'
>>> f"{878:e}"
'8.780000e+02'
>>> f"{878:o}"
'1556'
# Control the display of padding, filling, and precision of numbers
>>> 1 / 3
0.3333333333333333
>>> f"{1 / 3:.2f}"
'0.33'
>>> f"{69:4d}"
' 69'
>>> f"{69:=+8d}"
'+ 69'
>>> f"{69:0=8d}"
'00000069'
# Center text
>>> f"{'foo':^10}"
' foo '
And so many other things, since you can create your custom __format__.
Not affiliated, but in this regard, I quite love https://pyformat.info/ https://pyformat.info/ as a format cheat sheet.
- DonaldPShimoda 7y ago> I quite love https://pyformat.info/ https://pyformat.info/ as a format cheat sheet. I never knew this existed but that's awesome! Thanks for the link!
- pbreit 7y agoTo this novice, the "Old" way looks so much better.
- sametmax 7y agoWhat old way ? %, zfill, strftime, or some hack with len() ? Having a unified syntax with all formatting needs is a big deal.
- qquark 7y agoThis is maybe not directly visible in the parent comment, and particularly not on the website, that is compatible with old versions of python also, but to me there's a huge difference in usability also in the ability to use variable names in the current scope without additional verbose crap by default. This seems secondary to a lot of people, but to me that changes everything: >>> x = 1 >>> f"{x}" '1' This is much more readable than: >>> "{x}".format(x=x) '1' >>> "{}".format(x) '1' It makes the code immensely more readable than having to count parameters, especially for long strings with a lot of data in them. Counting is for computers, not programmers; I shouldn't have to count anything for such a trivial task. So, thanks to f"", no need for what I find to be an ugly additional call to .format(...), that is just visual clutter for most cases. The only reasons I could see for a call with a dedicated dict is data exfiltration from a user provided format string executed on python code they do not control, or renaming/subsetting of keywords for cleanliness. Both are special cases, and that's the effect the current implementation has, thankfully.
- collyw 7y agoI disagree, especially when using named parameters. The new style is too implicit.
- hannasanarion 7y agoHow is it implicit? Every insertion is expressed in exactly the place where it will print. It's way more explicit than having a placeholder and a value on completely different parts of the expression.
- collyw 7y ago> It's way more explicit than having a placeholder and a value on completely different parts of the expression. No its not.
- majewsky 7y ago"My name is {}, I'm {}'{}'' tall and live in {}".format(name, location, feet, inches) This error is much better hidden than in the equivalent: f"My name is {name}, I'm {location}'{feet}'' tall and live in {inches}."
- collyw 7y agoI did mention named parameters, you are using positional parameters to make your point. You don't even list the variables in your example. That seems pretty implicit to me. I think this is more explicit: "My name is {name}, I'm {feet} tall and live in {location}.".format(name="Bob", location="USA", feet=7)
- isaacremuant 7y agoYour example is not representative because you're using literals. Your actual example would be: "My name is {name}, I'm {feet} tall and live in {location}.".format(name=name, location=location, feet=feet) And with f-strings: f"My name is {name}, I'm {feet} tall and live in {location}." f-strings is clearly more readable, concise and actually faster to run.
- collyw 7y agoI agree, it seems to be getting away from "explicit over implicit".
- smugworth 7y agoI love F-strings, my only gripe is the chosen syntax for invoking them. For starters, F may or may not be capitalized, so these two lines are identical. F"My string with {interpolated_value}" f'My string with {interpolated_value}' Like using apostrophes or quotation marks to enclose strings (or F-strings), I find myself wasting time questioning the trivial notion of whether to capitalize or not. I think Groovy's syntax is great, where quotation marks denote an interpolated string, and apostrophes denote a plain old string. "This is my ${interpolated_value} string" 'This is my plain old string' But these are nitpicks, and it's really too late to implement something like that.
- kragen 7y ago> I think Groovy's syntax is great, where quotation marks denote an interpolated string, and apostrophes denote a plain old string. That's Perl's syntax, from about 15 years before Groovy, whippersnapper. Off my lawn, now.
- dragonwriter 7y agoYeah, Groovy got it from Ruby which got it from Perl.
- kragen 7y agoYeah, Ruby uses the doublequote/singlequote distinction from Perl, but Ruby tags variables to interpolate with #{}, while Groovy and Perl use $. Oh, although I guess Perl got that syntax from the Bourne shell…
- dragonwriter 7y ago> Yeah, Ruby uses the doublequote/singlequote distinction from Perl, but Ruby tags variables to interpolate with #{}, while Groovy and Perl use $. Huh, I could have sworn that I remembered that Groovy has taken it from Ruby. Incidentally, Ruby uses just # for variables, it uses #{} for arbitrary expressions. A common style prefers #{} even where # alone works, though.