An alternative to string interpolation

I sort of like this.

# ugly
msg = "I found %s files in %s directories" % (filecount,foldercount)

# better
def Str(*args): return "".join(str(x) for x in args)
msg = Str("I found ", filecount, " files in ", foldercount, " directories" )

You don’t have to call it “Str”, of course.


15 thoughts on “An alternative to string interpolation

  1. ‘Str’ version is impossible to translate.

    print(“I found {filecount} files in {foldercount} directories” % {“filecount”: x, “foldercount”: y})

    some hacky people use locals() for the mapping argument, but that can be a maintenance/security liability.

    • Oh my, I managed to mix up “%(style1)s” % {“style1”: 1} and “{style2}”.format(**{“style2”: 2}) completely. Shame on me.

      • I’ve seen “{style2}”.format(**{“style2”: 2}) elsewhere too. Why go through hoops and not write “{style2}”.format(style2=2) ?

  2. Why the hell you want so make so simple task as string joining so complicated?!

  3. I don’t see why the original is considered ugly. It’s shorter and separates the presentation from the values. What happens if you want to pad either number with zeroes or any other format?

  4. Or you can also simply use::

    msg = “I found ” + str(filecount) + ” files in ” + str(foldercount) + ” directories”

    (I always fear the cast to str())

    • The advantage of Str() is that it does not do string concatenation — it joins members of a list — so it should be faster.

      The downside of course is that it casts everything to strings, including things that are already strings. But I’m betting that there is hardly any cost to this, that Python is smart enough simply to do nothing at all, when it is asked to cast a string to a string.

      So I think the cost (in speed) of casting everything to strings is more than repaid by avoiding the overhead of string concatenation.

  5. “I found %(filecount)d files in %(foldercount)d directories” % vars()

  6. I tought
    “I found {} files in {} directories”.format(filecount,foldercount)
    was the python3 way of doing it. Or
    “I found {filecount} files in {foldercount} directories”.format(filecount=filecount,foldercount=foldercount)
    if you want more readability in the string and you dont mind some uglyness at the end…

  7. As others have said in the comments, your solution looks really ugly. In newer versions of python the preferred way of doing it would be (as someone else has already suggested):

    “I found {filecount} files in {foldercount} directories”.format(filecount=filecount,foldercount=foldercount)

  8. Why do you need a function for this? I inline this pattern all the time in JavaScript. It’s not too many characters. If you write it out explicitly each time, new people who have never seen your code should be able to understand it easier.

Comments are closed.