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?.

← Назад к списку