top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Format in Python

Introduction

String formatting Python 3 is a fundamental concept that allows you to create formatted strings by inserting values into placeholders within a string. The process controls how data is displayed and presented in your output. String formatting is essential to generate informative and user-friendly messages, reports, and data representations.

This guide covers various aspects of string format in Python, its syntax, types of formatting, formatting techniques, and practical examples.

Overview

String format in Python involves replacing placeholders in a string with actual values to create a formatted result. Python provides multiple methods for string formatting, including the str.format() method and the older % operator. The guide will primarily focus on the str.format() method, which is more versatile and recommended for modern Python code.

What Is String Formatting?

String formatting Python 3 is the process of creating strings with placeholders that are later filled with values. The "%" operator is used to format a collection of variables wrapped in a "tuple" (a fixed size list), as well as a format string including regular text and "argument specifiers," special symbols such as "%s" and "%d."

A Simple Demonstration of Python str.format() Method 

The str.format() method is versatile in formatting strings. It uses placeholders within a string and replaces them with values provided as arguments to the format() method. Let's explore this with an example:

code
name = "Eve"
age = 28

formatted_string = "Hello, my name is {}, and I am {} years old.".format(name, age)
print(formatted_string)

Output:

Hello, my name is Eve, and I am 28 years old.

{} is a placeholder that gets replaced by the values of name and age when the format(name, age) is called. This results in a formatted string with the values inserted at their respective positions.

Syntax of str.format() Function

The format function in Python allows you to create formatted strings with placeholders. Its syntax consists of placeholders within a string, represented by curly braces {}, and values to be inserted using the format() method.

Here's the basic format() function in python example:

code

formatted_string = "This is a {} with {} placeholders.".format(value1, value2)
  • "This is a {} with {} placeholders.": The string containing placeholders.

  • .format(value1, value2): The format() method used to replace placeholders with values.

Let's see a format() function in Python example:

code
name = "Frank"
age = 22

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

Output:

My name is Frank, and I am 22 years old.

In this example, the placeholders {} are replaced with the values name and age provided as arguments to the format() method.

Types of String Formatting in Python

There are several types of string format in Python, but we will mainly focus on the str.format() method. 

Formatting with the % Operator:

The % operator is an older method for string formatting in Python. It involves placeholders and format specifiers to format values and insert them into strings. For example:

code
name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)

Formatting with the format() String Method: 

The str.format() method is a versatile way to format strings using placeholders enclosed in curly braces {}. Values are inserted into these placeholders using the format() method. For example:

code
name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)

Python f-string Format

F-strings, introduced in Python 3.6, offer a concise way to embed expressions directly within string literals using {} placeholders. They make string formatting more readable and intuitive. For example:

code
name = "Charlie"
age = 35
formatted_string = f"Name: {name}, Age: {age}"

Formatting with the String Template Class: 

Template class is a simple way to create template strings with placeholders. Values are inserted into the placeholders using the substitute() method. 

For format() function in python example:

code
import string
name = "David"
template = string.Template("Name: $name")
formatted_string = template.substitute(name=name)

Using a Single Formatter:

You can use a single placeholder in a string to insert one value using the st.format() method. Here's an example:

python
Copy code
name = "Grace"
formatted_string = "Hello, my name is {}.".format(name)
print(formatted_string)

Output:

Hello, my name is Grace.

String format() with Multiple Placeholders 

You can use multiple placeholders within a single string and replace them with corresponding values using the str.format() method. Here's an example:

code
first_name = "Hannah"
last_name = "Smith"
age = 26

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

Output:

My name is Hannah Smith, and I am 26 years old.

String format() IndexError

If the Python format number of placeholders in the string does not match the number of values passed to the format() method, you will encounter an IndexError. For example:

code
name = "Isabella"
age = 30

# IndexError: tuple index out of range
formatted_string = "My name is {} and I am {} years old.".format(name)

Formatting Strings Using Escape Sequences 

Escape sequences are used to format in Python strings by adding special characters or control characters. Here are some commonly used escape sequences in Python:

  • \n: Newline character.

  • \t: Tab character.

  • \\: Backslash character.

  • \": Double quote character.

  • \': Single quote character.

Let's see an example:

code
message = "This is a multi-line\nstring with\ttabs and quotes: \"Hello!\" and \'Hi!\'"
print(message)

Output:

This is a multi-line

string with tabs and quotes: "Hello!" and 'Hi!'

Formatters with Positional and Keyword Arguments

In Python, you can specify the type of a placeholder using format specifiers within curly braces {}. Common format specifiers include:

  • s: String.

  • d or i: Integer.

  • f: Floating-point number.

  • x: Hexadecimal (base-16) representation.

Here's an example:

code
name = "Kelly"
age = 40
height = 5.9

formatted_string = "Name: {}, Age: {:d}, Height: {:.2f}".format(name, age, height)
print(formatted_string)

Output:

Name: Kelly, Age: 40, Height: 5.90

Here we use format specifiers to control the formatting of the values.

Type Specifying In Python

In Python, you can specify the type of a placeholder using format specifiers within curly braces {}. Common format specifiers include:

  • s: String.

  • d or i: Integer.

  • f: Python-format float Floating-point number.

  • x: Hexadecimal (base-16) representation.

Here's an example:

code
name = "Kelly"
age = 40
height = 5.9

formatted_string = "Name: {}, Age: {:d}, Height: {:.2f}".format(name, age, height)
print(formatted_string)

Output:

yaml

Copy code

Name: Kelly, Age: 40, Height: 5.90

In this example, we use format specifiers (:d for integers and :.2f for floating-point numbers) to control the formatting of the values.

Using %s – String Conversion via str() Prior to Formatting

In Python, you can use the %s format specifier to convert values to strings using the format function in Python before formatting. Here's an example:

code
name = "Liam"
age = 25

formatted_string = "Name: %s, Age: %s" % (str(name), str(age))
print(formatted_string)

Output:

yaml

Copy code

Name: Liam, Age: 25

In this example, we use %s to convert name and age to strings before formatting.

Using %c – Character Before Formatting

The %c format specifier formats a single character. Here's an example:

Python
Copy code
initial = 'M'

formatted_string = "My initial is %c." % initial
print(formatted_string)

Output:

My initial is M.

In this example, %c is used to format the character stored in the variable initial.

Using %i Signed Decimal Integer and %d Signed Decimal Integer (Base-10) Before Formatting

The %i and %d format specifiers are used for formatting signed decimal integers (base-10). They are used interchangeably. Here's an example:

code
number = 42

formatted_string = "The answer is %d." % number
print(formatted_string)

Output:

The answer is 42.

In this example, %d is used to format the integer number.

Another Useful Type Specifying

several other format specifiers are available for different data types and formatting options in Python. Some include:

  • %f: Floating-point number with decimal places.

  • %x: Hexadecimal representation.

  • %o: Octal representation.

  • %e or %E: Scientific notation.

  • %r: Represents a string using repr().

  • %u: Unsigned decimal integer.

  • %g or %G: Uses the shorter of %f or %e for formatting.

You can use these format specifiers to control how different types of data are formatted in your strings.

Convert Base-10 Decimal Integers to Floating-Point Numeric Constants

To convert base-10 decimal integers to Python format float-point numeric constants, you can use the %f format specifier. Here's an example:

code
integer_number = 123

formatted_string = "The floating-point representation is %.2f." % float(integer_number)
print(formatted_string)

Output:

The floating-point representation is 123.00.

%f is used in this example to format the integer integer_number as a floating-point number with two decimal places.

Type Specifying Errors

Using the wrong format specifier for a data type can result in type-specifying errors or unexpected output. For example

code
value = "123"

# Using the wrong format specifier (%d for a string)
formatted_string = "Value: %d" % value
print(formatted_string)

Output:

ValueError: unsupported format character 'd' (0x64) at index 10

The %d format specifier is used in this example,  for a string, resulting in a ValueError because it's incompatible with the data type.

Padding Substitutions or Generating Spaces

You can use padding to generate spaces or other characters to format strings. Padding is achieved by specifying the width and alignment within the format specifier. Here's an example:

code
name = "Nora"

# Padding with spaces (right-aligned)
formatted_string = "Name: {:>10}".format(name)
print(formatted_string)

# Padding with zeros (left-aligned)
number = 42
formatted_string = "Number: {:0>5}".format(number)
print(formatted_string)

Output:

Name:       Nora

Number: 00042

In the first example, we use {:>10} to right-align the name within a 10-character-wide field, adding spaces as padding. In the second example, {:0>5} left-aligns the number with leading zeros to fill a 5-character-wide field.

Using a dictionary for string formatting

You can use dictionaries to format strings by accessing values using keys. Here's an example:

code
student_info = {"name": "Oliver", "age": 20}

formatted_string = "Student: {name}, Age: {age}".format(**student_info)
print(formatted_string)

Output:

Student: Oliver, Age: 20

In this example, we define a dictionary student_info, and then we use {name} and {age} placeholders in the string and replace them with corresponding values from the dictionary using the format() method.

Python format() with list

You can use a list to format strings by accessing values using indexing. Here's an example:

code
student_data = ["Emma," 22]

formatted_string = "Student: {}, Age: {}".format(student_data[0], student_data[1])
print(formatted_string)

Output:

Student: Emma, Age: 22

In this example, we use indexing (student_data[0] and student_data[1]) to access values from the list and replace the placeholders in the string.

Conclusion

String format in Python creates well-structured and informative output. You can use various techniques like str.format(), python f-string format, and % formatting to format strings according to your needs. Understanding format specifiers, escape sequences, padding, and Python string formatting cheat sheets can help you control the appearance of your formatted strings.

By mastering string formatting, you can enhance the readability and usability of your Python programs and generate user-friendly output.

FAQs

1. How does the str.format() method work in Python?

The str.format() method allows you to create formatted strings with placeholders enclosed in curly braces {}. You replace these placeholders with values using the format() method.

2. What are f-strings, and how do they simplify string formatting in Python?

F-strings are a feature introduced in Python 3.6 that allows you to embed expressions inside string literals using {} placeholders. They simplify string formatting by providing a concise and readable way to insert values into strings.

3. What is the difference between single and double curly braces in string formatting with str.format()?

Single curly braces {} are used as placeholders for values to be inserted. Double curly braces {{}} are used to include literal curly braces in the formatted string.

4. How can I format strings with both positional and keyword arguments using str.format()?

You can mix positional and keyword arguments when using str.format() by providing values in both ways. Positional arguments are replaced in the order of appearance, while keyword arguments are replaced based on their names.

Leave a Reply

Your email address will not be published. Required fields are marked *