title: String formatting: % vs. .format vs. f-string literal
body: <p>There are various string formatting methods:</p>
  <ul>
  <li>Python &lt;2.6: <code>&quot;Hello %s&quot; % name</code></li>
  <li>Python 2.6+: <code>&quot;Hello {}&quot;.format(name)</code>   (uses <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow noreferrer"><code>str.format</code></a>)</li>
  <li>Python 3.6+: <code>f&quot;{name}&quot;</code>   (uses f-strings)</li>
  </ul>
  <p>Which is better, and for what situations?</p>
  <hr />
  <ol>
  <li><p>The following methods have the same outcome, so what is the difference?</p>
  <pre><code>name = &quot;Alice&quot;
  
  &quot;Hello %s&quot; % name
  &quot;Hello {0}&quot;.format(name)
  f&quot;Hello {name}&quot;
  
  # Using named arguments:
  &quot;Hello %(kwarg)s&quot; % {'kwarg': name}
  &quot;Hello {kwarg}&quot;.format(kwarg=name)
  f&quot;Hello {name}&quot;
  </code></pre>
  </li>
  <li><p>When does string formatting run, and how do I avoid a runtime performance penalty?</p>
  </li>
  </ol>
  <hr />
  <p><sub>If you are trying to close a duplicate question that is just looking for a way to format a string, please use <a href="https://stackoverflow.com/questions/2960772">How do I put a variable’s value inside a string?</a>.</sub></p>