4 ms·
I have mixed feeling about this. This will be the FOURTH way of formatting strings in Python. The other formattings will never go away.
by Walkman 11y ago
I have mixed feeling about this. This will be the FOURTH way of formatting strings in Python. The other formattings will never go away.
- orionblastar 11y agoI think they keep the other formatting for backward compatibility in legacy code.
- bhaak 11y agoWhat's the fourth way? The article only mentions three.
- nothrabannosir 11y agoNot the op but Im guessing just using + (which calls .__str__(), iirc?)
- richardwhiuk 11y ago+ doesn't call __str__ internally. e.g the following is an error. a = 4 "a: " + a You have to do: "a: " + str(a)
- barely_stubbell 11y agoI agree that + is likely the 4th way. A minor correction to your comment: "+" calls the __add__ method (big surprise) - just fyi
- rdtsc 11y ago4th way is with templates: >>> from string import Template >>> s = Template('$who likes $what') >>> s.substitute(who='tim', what='kung pao') This will probably be TIL for many people. It is a surprisingly hidden feature. I for one, still like the "%s" % x instead of "{0}".format(x). It is simply shorter and I already know or use printf for C in other parts of the project. But with the new f"..." interpolation, I can see liking that more. I am all for being as concise as possible while still being explicit (if that makes any sense at all ;-) ).
- toyg 11y agoI've always found templates way overkill for most of my needs, but they cover a specific and legitimate use-case (large and complex blocks of text). In the same way, .format() solved the problem of inconsistency and bugs happening all the time with %. It was a restriction and formalization effort, trying to root out bad practices and hence slightly more explicit, but it made sense. The new f'' IMHO does not solve anything beyond pandering to developer laziness. It will likely introduce bugs in places where developers are not clear about the context ("oh, I thought we didn't have a 'x' var at this point, turns out we do!"), because (from what I understand) it takes away the ability to define which variables should be considered. Luckily it will take a while before it percolates in any significant library, but I sincerely hope it just doesn't gain much traction.
- deleted 11y ago[deleted]