Python Language String Formatting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.


Got any Python Language Question?