Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

format - sprintf

  • %
  • %s
  • f
  • {}
  • format
  • sprintf
age = 42.12
name = 'Foo Bar'

str_concatenate = "The user " + name + " was born " + str(age) + " years ago."
print(str_concatenate)

str_percentage = "The user %s was born %s years ago." % (name, age)
print(str_percentage)

str_format = "The user {} was born {} years ago.".format(name, age)
print(str_format)

str_f_string = f"The user {name} was born {age} years ago."
print(str_f_string)

The user Foo Bar was born 42.12 years ago.
The user Foo Bar was born 42.12 years ago.
The user Foo Bar was born 42.12 years ago.
The user Foo Bar was born 42.12 years ago.
  • When using % to print more than one value, put the values in parentheses forming a tuple.
  • In version 2.6 and below you need to write {0} {1} etc, as a placeholder of the format method.
  • f-strings were added in Python 3.6 (released on 2016-12-23)