Stats

2251 Contributors: 66 Friday, July 7, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

String Formatting

Introduction

When storing and transforming data for humans to see, string formatting can become very important. Python offers a wide variety of string formatting methods which are outlined in this topic.

Syntax

  • "{}".format(42) ==> "42"
  • "{0}".format(42) ==> "42"
  • "{0:.2f}".format(42) ==> "42.00"
  • "{0:.0f}".format(42.1234) ==> "42"
  • "{answer}".format(no_answer=41, answer=42) ==> "42"
  • "{answer:.2f}".format(no_answer=41, answer=42) ==> "42.00"
  • "{[key]}".format({'key': 'value'}) ==> "value"
  • "{[1]}".format(['zero', 'one', 'two']) ==> "one"
  • "{answer} = {answer}".format(answer=42) ==> "42 = 42"
  • ' '.join(['stack', 'overflow']) ==> "stack overflow"

Remarks

  • Should check out PyFormat.info for a very thorough and gentle introduction/explanation of how it works.

Related Examples