String formatting is an essential concept in Python programming. It allows you to insert and format text dynamically in strings. In this comprehensive guide, we will explore the ins and outs of string formatting in Python.

Overview of String Formatting

String formatting provides a more flexible way to create strings. With string formatting, you can:

  • Insert variables and expressions into strings
  • Format numbers and strings
  • Align text
  • Control float precision

Instead of concatenating strings with +, you use format strings with curly braces {} as placeholders. You then pass variables into the format method to insert them.

Here is a basic string formatting example:

name = "John"
age = 30
print("My name is {0}. I am {1} years old.".format(name, age))

Output:

My name is John. I am 30 years old.

This allows you to construct strings dynamically and keep your code DRY.

There are several ways to format strings in Python:

  • The format() method
  • f-strings
  • %-formatting
  • Template strings

We will cover each approach in detail.

The String format() Method

The format() method is one of the most common ways to format strings in Python.

It works by passing variables into the placeholder fields {}. You can optionally specify an index for each placeholder:

print("My name is {0}. I am {1} years old.".format(name, age)) 

You can also use keyword arguments to clean up the syntax:

print("My name is {name}. I am {age} years old.".format(name=name, age=age))

Some key things the str.format() method can do:

  • Insert variables into strings
  • Format numbers and strings
  • Align text with <, ^, >
  • Precision formatting for floats

Let‘s look at some examples!

Inserting Variables

As you saw earlier, you can insert any variable into a string with {}:

name = "John"
age = 30  

print("My name is {0}. I am {1} years old.".format(name, age))

You can also directly reference variables without numbering the placeholders:

print("My name is {name}. I am {age} years old.".format(name=name, age=age)) 

Formatting Numbers

You can format numbers to control padding and decimal places:

value = 12345.6789

print("The number is {0:>10.2f}".format(value)) # Right align, 10 width, 2 decimal places 

Output:

     12345.68

Some useful formatting codes:

  • {n:d} – Integers with minimum n digits (pads with 0‘s)
  • {n:f} – Floats to n decimal places
  • {:+f} – Show + sign for positive numbers
  • {:,} – Add thousands separators

See the end for a full reference.

Aligning Text

You can align text left, right or center with <, ^ and >:

text = "Hello"

print("|{0:<10}|{0:^10}|{0:>10}|".format(text))

Output:

|Hello     |  Hello   |     Hello|

This is useful for formatting text in nice columns.

Precision of Floats

You can also specify the precision of floats:

pi = 3.1415926
print("Pi = {0:.3f}".format(pi)) # .3 = 3 digits after decimal

Output:

Pi = 3.142

This allows fine control over float formatting.

Summary – format()

To summarize, the format() method provides extensive control for formatting strings. It‘s very versatile – you can combine text alignment, variable insertion, number formatting and float precision.

f-strings

Python 3.6 introduced a new string formatting approach called formatted string literals or f-strings.

f-strings provide a concise and convenient way to format strings.

They work by prefixing the string with f and inserting expressions inside curly braces {}:

name = "John"
age = 30
print(f"My name is {name}. Next year I will be {age + 1}.") 

Output:

My name is John. Next year I will be 31.  

Some key features of f-strings:

  • Insert variables and expressions directly in {}
  • Evaluation happens at run time
  • Cleaner syntax compared to format()
  • Format numbers, align text and precision

Let‘s take a look at some examples of how to leverage f-strings.

Inserting Expressions

You can insert any expression inside the {}:

import math
print(f"The value of pi is: {math.pi:.3f}")

Output:

The value of pi is: 3.142

This evaluates math.pi at runtime and formats it to 3 decimals.

You can write cleaner code without temporaries.

Evaluation Happens at Run Time

One advantage of f-strings is evaluation happens at run time:

x = 10
print(f"I said x = {x}") # Returns current value of x

x = 20
print(f"Now I say x = {x}") # Returns updated value of x

Output:

I said x = 10  
Now I say x = 20

So f-strings are dynamic and expressive.

Format Numbers and Align Text

You get all the same formatting codes as the format() method:

sales = 12345.6789

print(f"Sales were {sales:>10.2f} last month!") # Right align, pad, truncate

Output:

 Sales were    12345.68 last month!

And text:

text = "Hello" 

print(f"|{text:<10}|{text:^10}|{text:>10}|") # Align

Output:

|Hello     |  Hello   |     Hello|

So f-strings provide a concise way to format strings without losing any functionality.

Summary – f-strings

In summary, f-strings provide:

  • Concise syntax for string formatting
  • Insert expressions and variables directly in {}
  • Evaluate expressions at run time
  • Format numbers, align text and control float precision

%-Format Strings

The % operator can also be used for string formatting in Python. This old style is provided for backward compatibility but is less flexible than format() and f-strings.

Each %s and %d in the string acts as a placeholder. You then supply variables as a tuple argument to replace the placeholders:

name = "John"
age = 30
print("My name is %s. Next year I will be %d." % (name, age+1))  

Output:

My name is John. Next year I will be 31.

Some placeholder types:

  • %s – Strings
  • %d – Integers
  • %f – Floating point numbers

You can also align text and precision format floats:

number = 12345.6789
print("The number is %10.2f" % number) # Right align, pad, round  

So %-formatting serves as a simpler legacy approach to string formatting in Python.

Template Strings

Another formatting option is to use Python template strings. This approach resembles template languages used in web frameworks like Django, Jinja, etc.

Template strings are marked up using $ placeholders:

from string import Template

person = {"name": "John", "age": 30}

t = Template("My name is $name. Next year I will be $age.")  
print(t.substitute(person))

Common use cases for templates:

  • Simple string formatting
  • Bulk email templates
  • Code generation templates
  • Text processing

Template strings provide basic string formatting and substitution functionality. However, format() and f-strings are more flexible for most use cases.

PEP 498 – Literal String Interpolation

An upcoming Python enhancement proposal PEP 498 aims to simplify f-strings further.

Some proposed updates:

  • Omit the f prefix altogether:

    print("{name} is {age} years old.")
  • Allow = in expressions:

    print("{total = price * tax}") 

So f-string syntax may improve to be even more readable. This PEP is still in draft status but shows the direction of Python‘s string formatting language.

Formatting Reference Table

Here is a quick reference guide for padding, precision and types with both format() and %-formatting:

Code Meaning
{n:d} or %d Integers with minimum width n
{n:f} or %f Floats to n decimal places
{:+f} Show + sign for positive numbers
{:,} Thousands separator
{:>10} or %-10s Right align to 10 characters
{:<10} or %-10s Left align
{:^10} or %10s Center align

And many more options are available. Consult the reference for full details.

Conclusion

String formatting is essential in Python programming. The main methods include:

  • format() – Flexible and feature-rich
  • f-strings – Concise syntax and expressions
  • %-formatting – Legacy approach
  • Template strings – Simple substitutions

The format() method and f-strings provide the best balance of control vs brevity. Learning string formatting deeply will help you write more robust and maintainable Python codebases.

Similar Posts