Hacker News new | past | comments | ask | show | jobs | submit login

What's the fourth way? The article only mentions three.



4th 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 ;-) ).


I'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.


Not the op but Im guessing just using + (which calls .__str__(), iirc?)


+ doesn't call __str__ internally.

e.g the following is an error.

  a = 4
  "a: " + a
You have to do:

  "a: " + str(a)


I agree that + is likely the 4th way.

A minor correction to your comment: "+" calls the __add__ method (big surprise) - just fyi




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: