pythonperformancestring-formattingf-string

String formatting: % vs. .format vs. f-string literal


There are various string formatting methods:

Which is better, and for what situations?


  1. The following methods have the same outcome, so what is the difference?

    name = "Alice"
    
    "Hello %s" % name
    "Hello {0}".format(name)
    f"Hello {name}"
    
    # Using named arguments:
    "Hello %(kwarg)s" % {'kwarg': name}
    "Hello {kwarg}".format(kwarg=name)
    f"Hello {name}"
    
  2. When does string formatting run, and how do I avoid a runtime performance penalty?


If you are trying to close a duplicate question that is just looking for a way to format a string, please use How do I put a variable’s value inside a string?.


Solution

  • To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

    "Hello %s" % name
    

    yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

    "Hello %s" % (name,)   # supply the single argument as a single-item tuple
    

    which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

    Only use it for backwards compatibility with Python 2.5.


    To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression log.debug("some debug info: %s" % some_info) will first evaluate the string to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().