Python format()

Python format() function and .format() method are powerful for formatting strings, numbers, and other data types. They provide flexibility and precision, allowing you to create dynamic and professional-looking output. You can handle various formatting tasks in your Python programs by mastering these techniques.
Table of Contents

Understanding Python format() Function

Python format() is a built-in function used to format strings. It provides a way to create formatted output by substituting values into placeholders within a string template. The placeholders are defined using curly braces {}, and you can specify various formatting options within these braces. Python format() is a powerful tool for creating nicely formatted strings for display or logging, as it allows you to control the alignment, padding, precision, and output type.

Syntax of Python format()

formatted_string = “{}”.format(value)

Explanation

  • formatted_string: Variable will store the resulting formatted string.
  • "{}": String template with placeholders ({}) for values to be inserted.
  • .format(): Method that performs the string formatting.
  • value: Value to be inserted into the placeholder. It is passed as parameter to format().

Example of Python format()

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

Explanation

  • name = "Alice": Initializes a string variable name with the value “Alice”.
  • age = 30: Initializes an integer variable age with the value 30.
  • formatted_string = "My name is {} and I am {} years old.".format(name, age): Uses the .format() method to create a formatted string, substituting name and age into the placeholders.
  • print(formatted_string): Prints the formatted string.

Output

My name is Alice and I am 30 years old.


format() Parameters

Python format() function can accept multiple parameters corresponding to the values you want to insert into the string template. These parameters are passed inside the parentheses of the .format() method, separated by commas. You use curly braces {} as placeholders for these values within the string template. You can also use numbers inside the braces (e.g., {0}, {1}) to refer to specific parameters by their position, or you can use names if you pass keyword arguments to .format().

Syntax

formatted_string = “{} {} … {}”.format(value1, value2, …, keyword1=value_kw1, keyword2=value_kw2, …)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{} {} ... {}": String template with placeholders.
  • .format(): Method formats the string using the provided values.
  • value1, value2, ...: Positional arguments passed to .format().
  • keyword1=value_kw1, keyword2=value_kw2, ...: Keyword arguments passed to .format().

Example

formatted_string = "I have a {fruit} and a {vegetable}.".format(fruit="apple", vegetable="carrot")
print(formatted_string)

Explanation

  • formatted_string = "I have a {fruit} and a {vegetable}.".format(fruit="apple", vegetable="carrot"): Creates a formatted string using keyword arguments to fill in the placeholders.
  • print(formatted_string): Prints the formatted string.

Output

I have a apple and a carrot.


format() Return Type

When used with a string, the Python format() method returns a new formatted string in which the placeholders in the original string have been replaced with the provided values. It doesn’t modify the original string but creates a new one with the substitutions made. The type of the inserted values can be anything; format() will automatically convert them to their string representations before inserting them.

Syntax

new_string = “{}”.format(value)

Explanation

  • new_string: Variable will store the new formatted string returned by .format().
  • "{}": String template containing a placeholder.
  • .format(): Method returns a new string with the placeholder replaced by value.
  • value: Value that will be inserted into the placeholder. It is passed as parameter to format().

Example

result = "The result is: {}".format(42)
print(result)

Explanation

  • result = "The result is: {}".format(42): Creates a new string where the placeholder is replaced with the string representation of 42.
  • print(result): Prints the new string stored in result.

Output

The result is: 42


Numeric Formatting using format()

Python format() function provides powerful options for formatting numeric values. You can control the number of decimal places, add padding, include commas as thousands separators, and more. To format a number, use a colon : inside the curly brace placeholder, followed by the formatting specifier. For example, :.2f formats a number with two decimal places, :d formats an integer in decimal (base-10) format, and :, adds commas as thousands separators.

Syntax

formatted_string = “{:formatting_specifier}”.format(number)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{:formatting_specifier}": String template with a placeholder containing a formatting specifier.
  • .format(): Method formats the number according to the specifier.
  • number: Numeric value to be formatted. It is passed as parameter to format().

Example

pi = 3.14159
formatted_pi = "{:.2f}".format(pi)
print(formatted_pi)

big_number = 1234567
formatted_number = "{:,}".format(big_number)
print(formatted_number)

Explanation

  • pi = 3.14159: Initializes a float variable pi with the value of pi.
  • formatted_pi = "{:.2f}".format(pi): Formats pi to two decimal places and stores the result in formatted_pi.
  • print(formatted_pi): Prints the formatted value of pi.
  • big_number = 1234567: Initializes an integer variable big_number.
  • formatted_number = "{:,}".format(big_number): Formats big_number with commas as thousands separators.
  • print(formatted_number): Prints the formatted number.

Output

3.14
1,234,567


Number Formatting with Sign

When using Python format(), you can control how numeric signs are displayed in the formatted output. By default, a minus sign is shown for negative numbers, but no sign is displayed for positive numbers. If you want always to show a sign, you can use the + specifier for positive numbers and for negative numbers.

Syntax

formatted_string = “{:+f}”.format(number)

Explanation

  • formatted_string: Variable will store the formatted string with the sign.
  • "{:+f}": String template with a placeholder that includes the + sign specifier for numeric values.
  • .format(): Method formats the number, including the sign.
  • number: Numeric value to be formatted. It is passed as parameter to format().

Example

positive_num = 42
negative_num = -42

formatted_positive = "{:+}".format(positive_num)
formatted_negative = "{:}".format(negative_num)

print(formatted_positive)
print(formatted_negative)

Explanation

  • positive_num = 42: Initializes a positive integer.
  • negative_num = -42: Initializes a negative integer.
  • formatted_positive = "{:+}".format(positive_num): Formats positive_num to include a plus sign.
  • formatted_negative = "{:}".format(negative_num): Formatsnegative_num` which will have a minus sign by default.
  • print(formatted_positive): Prints the formatted positive number.
  • print(formatted_negative): Prints the formatted negative number.

Output

+42
-42


Number Formatting with Precision

Precision in formatting refers to the number of decimal places to display for floating-point numbers. When using Python format(), you can specify the precision by using the . followed by the number of decimal places and the letter f inside the placeholder. For example, :.3f will format a float with three digits after the decimal point. This is commonly used when you need to round numbers to a specific number of decimal places for display or reporting.

Syntax

formatted_string = “{:.precisionf}”.format(float_number)

Explanation

  • formatted_string: Variable will store the formatted string with the specified precision.
  • "{:.precisionf}": String template with a placeholder that includes the precision specifier.
  • .format(): Method formats the floating-point number to the specified precision.
  • float_number: Floating-point number to be formatted. It is passed as parameter to format().

Example

number = 12.34567
formatted_number = "{:.2f}".format(number)
print(formatted_number)

Explanation

  • number = 12.34567: Initializes a float variable number.
  • formatted_number = "{:.2f}".format(number): Formats number to two decimal places.
  • print(formatted_number): Prints the formatted number.

Output

12.35


Formatting with Alignment and Padding

Python format() allows you to align text within a certain width and pad it with spaces or other characters. To align text, you use < for left alignment, > for right alignment, and ^ for center alignment, followed by the desired width inside the placeholder. Specify the padding character and width before the alignment symbol to add padding. This is particularly useful when creating neatly formatted tables or aligning text in columns.

Syntax

# Left alignment with padding
formatted_string = "{:char<width}".format(string)

# Right alignment with padding
formatted_string = "{:char>width}".format(string)

# Center alignment with padding
formatted_string = "{:char^width}".format(string)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{:char<width}", "{:char>width}", "{:char^width}": String templates with placeholders for alignment and padding.
  • char: Padding character (optional, defaults to space).
  • <, >, ^: Alignment symbols for left, right, and center, respectively.
  • width: Total width of the field.
  • .format(): Method formats the string with the specified alignment and padding.
  • string: String to be formatted. It is passed as parameter to format().

Example

text = "hello"
left_aligned = "{:*<10}".format(text)
right_aligned = "{:->10}".format(text)
center_aligned = "{:.^10}".format(text)

print(left_aligned)
print(right_aligned)
print(center_aligned)

Explanation

  • text = "hello": Initializes a string variable text.
  • left_aligned = "{:*<10}".format(text): Formats text with left alignment, padding with *, in a field of width 10.
  • right_aligned = "{:->10}".format(text): Formats text with right alignment, padding with -, in a field of width 10.
  • center_aligned = "{:.^10}".format(text): Formats text with center alignment, padding with ., in a field of width 10.
  • print(left_aligned): Prints the left-aligned string.
  • print(right_aligned): Prints the right-aligned string.
  • print(center_aligned): Prints the center-aligned string.

Output

hello*****
—–hello
..hello…


Using .Format() Method

The .format() method is a string method in Python that is used to create formatted strings. It replaces placeholders in a string template with the values you provide. Placeholders are denoted by curly braces {}. You can use Python format() to insert values into a string in a specific order or use numbers or names inside the placeholders to specify the order or refer to keyword arguments. This method provides a readable and flexible way to construct strings containing variable content.

Syntax

formatted_string = “template string {}”.format(value)

Explanation

  • formatted_string: Variable will store the resulting formatted string.
  • "template string {}": String template containing placeholders.
  • .format(): Method formats the string by replacing placeholders with values.
  • value: Value to be inserted into the placeholder. It is passed as parameter to .format().

Example

greeting = "Hello, {}".format("Alice")
print(greeting)

Explanation

  • greeting = "Hello, {}".format("Alice"): Creates a formatted string where “Alice” replaces the {} placeholder.
  • print(greeting): Prints the formatted string.

Output

Hello, Alice


Using a Single Formatter

When using Python format() with a single placeholder in the string template, you can pass a single value directly to the .format() method. Python will replace the placeholder with the string representation of that value. If you need to apply specific formatting to the value, you can include a format specifier inside the placeholder, following a colon :.

Syntax

formatted_string = “{}”.format(value)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{}": String template with a single placeholder.
  • .format(): Method inserts the value into the placeholder.
  • value: Value to be formatted and inserted. It is passed as parameter to .format().

Example

formatted_string = "The value is {:.2f}".format(3.14159)
print(formatted_string)

Explanation

  • formatted_string = "The value is {:.2f}".format(3.14159): Formats the float 3.14159 to two decimal places.
  • print(formatted_string): Prints the formatted string.

Output

The value is 3.14


String format() with Multiple Placeholders

When your string template has multiple placeholders, the Python format() method allows you to replace each placeholder with a corresponding value. You pass multiple arguments to .format() in the order that matches the placeholders in the string. Each argument is then inserted into the template in place of the placeholder. You can also use numbers inside the placeholders (like {0}, {1}) to specify the order explicitly or to reuse arguments.

Syntax

formatted_string = “{} {} {}”.format(value1, value2, value3)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{} {} {}": String template with multiple placeholders.
  • .format(): Method replaces the placeholders with the provided values.
  • value1, value2, value3: Values to be inserted into the placeholders, in order. Each value is passed as parameter to .format().

Example

sentence = "{} ate {} {}".format("Alice", 3, "apples")
print(sentence)

Explanation

  • sentence = "{} ate {} {}".format("Alice", 3, "apples"): Creates a formatted string by inserting the values “Alice”, 3, and “apples” into the placeholders.
  • print(sentence): Prints the formatted string.

Output

Alice ate 3 apples


String format() IndexError

When using the Python format() method, an IndexError can occur if you refer to a positional argument that doesn’t exist in the .format() call. For example, if your template string has a placeholder {1} but you only provide one argument to .format(), Python will raise an IndexError because there is no argument at index 1. To avoid this error, ensure that your placeholders correspond to the number and order of arguments you provide.

Syntax

formatted_string = “{1}”.format(value0) # Incorrect: {1} refers to the second argument, but only one is provided

Explanation

  • formatted_string: Variable would store the formatted string if the syntax were correct.
  • "{1}": String template with an indexed placeholder that refers to the second argument.
  • .format(): Method attempts to replace the placeholder with a value.
  • value0: First (and only) value provided, corresponding to index 0. Passing only one value will raise IndexError in this case.

Example

try:
    error_string = "{0} {1} {2}".format("apple", "banana")
    print(error_string)
except IndexError as e:
    print(f"Error: {e}")

Explanation

  • try:: Block attempts to execute code that might raise an IndexError.
  • error_string = "{0} {1} {2}".format("apple", "banana"): Attempts to format a string with three placeholders but only two arguments, causing an IndexError.
  • print(error_string): Print the formatted string if no error occurred.
  • except IndexError as e:: Block catches the IndexError if it is raised.
  • print(f"Error: {e}"): Prints the error message.

Output

Error: tuple index out of range


Formatting Strings using Escape Sequences

Escape sequences are special characters used in strings to represent certain non-printable or special characters, such as a newline or a tab. When using Python format(), you can include escape sequences in your string template. For example, \n represents a newline character, and \t represents a tab character. These sequences are interpreted just like in any other Python string.

Syntax

formatted_string = “line1\nline2\t{}”.format(value)

Explanation

  • formatted_string: Variable will store the formatted string containing escape sequences.
  • "line1\nline2\t{}": String template that includes newline (\n) and tab (\t) escape sequences.
  • .format(): Method inserts the value into the template.
  • value: Value to be inserted into the placeholder. It is passed as parameter to .format().

Example

formatted_string = "First Line\nSecond Line\tIndented: {}".format(10)
print(formatted_string)

Explanation

  • formatted_string = "First Line\nSecond Line\tIndented: {}".format(10): Creates a formatted string that includes a newline and a tab, with 10 inserted at the placeholder.
  • print(formatted_string): Prints the formatted string, interpreting the escape sequences.

Output

First Line
Second Line Indented: 10


Formatters with Positional and Keyword Arguments

You can combine positional and keyword arguments using the Python format() method to fill in placeholders in your string template. Positional arguments are referred to by their index (starting from 0) within the curly braces, while keyword arguments are referred to by their name. When you mix both types, you must list all positional arguments in .format() before any keyword arguments.

Syntax

formatted_string = “{1} {0} {keyword}”.format(pos_value, another_pos_value, keyword=kw_value)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{1} {0} {keyword}": String template uses both numbered and named placeholders.
  • .format(): Method fills in the placeholders with the provided values.
  • pos_value: First positional argument (index 0). You need to pass all the positional parameters first in .format().
  • another_pos_value: Second positional argument (index 1).
  • keyword=kw_value: Keyword argument, referred to by the name keyword.

Example

formatted = "{1} {0} is {age} years old".format("Alice", "Bob", age=30)
print(formatted)

Explanation

  • formatted = "{1} {0} is {age} years old".format("Alice", "Bob", age=30): Formats the string by inserting “Bob” at {1}, “Alice” at {0}, and 30 at {age}.
  • print(formatted): Prints the formatted string.

Output

Bob Alice is 30 years old


Type Specifying in Python

Type specifying in Python format() lets you control how values are represented in the output string. You can specify the type by using a type code after the colon : inside the placeholder. Common type codes include s for strings, d for integers, f for floating-point numbers, and b, o, x, X for binary, octal, and hexadecimal representations, respectively. Here are some common type specifying used in Python.


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

In Python’s older style of string formatting (using the % operator), the %s placeholder inserts a string representation of a value into a string. It calls the str() function on the value to convert it to a string before inserting it. This is a simple way to include any object’s string representation in your formatted string.

Syntax

formatted_string = “%s” % value

Explanation

  • formatted_string: Variable will store the formatted string.
  • "%s": String template with a %s placeholder, which stands for a string value.
  • %: Operator is used for string formatting.
  • value: Value to be converted to a string and inserted. It is used with % operator.

Example

name = "Alice"
formatted_string = "Hello, %s!" % name
print(formatted_string)

Explanation

  • name = "Alice": Initializes a string variable name.
  • formatted_string = "Hello, %s!" % name: Formats the string using %s to insert the value of name.
  • print(formatted_string): Prints the formatted string.

Output

Hello, Alice!


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

Both %i and %d are used in Python’s older-style string formatting to represent signed decimal integers. They are equivalent. When you use these placeholders, the corresponding integer value is inserted into the string. If the value is not an integer, Python will attempt to convert it to one.

Syntax

formatted_string = “%d” % integer_value # or %i

Explanation

  • formatted_string: Variable will store the formatted string.
  • "%d" or "%i": String template with a %d or %i placeholder for an integer.
  • %: Operator is used for string formatting.
  • integer_value: Integer value to be inserted. It is used with % operator.

Example

age = 25
formatted_string = "Age: %d" % age
print(formatted_string)
formatted_string_i = "Age: %i" % age
print(formatted_string_i)

Explanation

  • age = 25: Initializes an integer variable age.
  • formatted_string = "Age: %d" % age: Formats the string using %d to insert the value of age.
  • print(formatted_string): Prints the formatted string.
  • formatted_string_i = "Age: %i" % age: Formats the string using %i to insert the value of age.
  • print(formatted_string_i): Prints the formatted string.

Output

Age: 25
Age: 25


Using %c– Character Prior to Formatting

The %c placeholder is used in Python’s older-style string formatting to insert a single character into a string. The corresponding value can be an integer representing a Unicode code point or a single-character string. This is useful when you need to format a string that includes individual characters based on their numeric code or to ensure that a variable is represented as a single character.

Syntax

formatted_string = “%c” % character_value

Explanation

  • formatted_string: Variable will store the formatted string.
  • "%c": String template with a %c placeholder for a character.
  • %: Operator is used for string formatting.
  • character_value: Integer or single-character string to be inserted. It is used with % operator.

Example

letter = 65  # ASCII for 'A'
formatted_string = "The letter is: %c" % letter
print(formatted_string)

Explanation

  • letter = 65: Initializes an integer variable letter with the ASCII value for ‘A’.
  • formatted_string = "The letter is: %c" % letter: Formats the string using %c to insert the character corresponding to letter.
  • print(formatted_string): Prints the formatted string.

Output

The letter is: A


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

In Python, you can format floating-point numbers within a string using type specifiers like f for fixed-point notation, e or E for scientific notation. These specifiers are used inside placeholders using the .format() method or f-strings. They allow you to control the number of decimal places, the notation (e.g., whether to use scientific notation), and other aspects of how the float is represented in the string.

Syntax

formatted_string = “{:.nf}”.format(float_value) # Fixed-point notation, n decimal places
formatted_string = “{:.ne}”.format(float_value) # Scientific notation, n decimal places

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{:.nf}" or "{:.ne}": String templates with placeholders that include type specifiers for floating-point numbers.
  • .format(): Method formats the string.
  • float_value: Floating-point value to be formatted. It is passed as input to .format().

Example

number = 3.14159
formatted_fixed = "{:.2f}".format(number)  # Fixed-point with 2 decimal places
formatted_sci = "{:.2e}".format(number)  # Scientific notation with 2 decimal places

print(formatted_fixed)
print(formatted_sci)

Explanation

  • number = 3.14159: Initializes a float variable number.
  • formatted_fixed = "{:.2f}".format(number): Formats number in fixed-point notation with 2 decimal places.
  • formatted_sci = "{:.2e}".format(number): Formats number in scientific notation with 2 decimal places.
  • print(formatted_fixed): Prints the formatted number in fixed-point notation.
  • print(formatted_sci): Prints the formatted number in scientific notation.

Output

3.14
3.14e+00


Type Specifying Errors

When using type specifiers in string formatting, it’s possible to encounter errors if the specifier doesn’t match the formatted value type. For instance, using an integer specifier like %d with a string will raise a TypeError. Similarly, using a string specifier with an object that doesn’t have a string representation can also cause errors. To avoid these, you should always ensure that the type specifier you use is appropriate for the value you’re formatting.

Syntax

# Incorrect usage (may raise TypeError)
formatted_string = “%d”.format(string_value)

Explanation

  • formatted_string: Variable would store the formatted string if no error occurred.
  • "%d": String template with an integer specifier.
  • .format(): Method attempts to format the string_value as an integer.
  • string_value: String value, which is incompatible with the %d specifier. It is passed as parameter to .format().

Example

try:
    error_string = "%d".format("hello")
    print(error_string)
except TypeError as e:
    print(f"Error: {e}")

Explanation

  • try:: Block attempts to execute code that might raise a TypeError.
  • error_string = "%d".format("hello"): Format a string using an integer specifier, causing a TypeError.
  • print(error_string): Print the formatted string if no error occurred.
  • except TypeError as e:: Block catches the TypeError if it is raised.
  • print(f"Error: {e}"): Prints the error message.

Output

Error: %d format: a number is required, not str


Padding Substitutions or Generating Spaces

Padding in string formatting refers to adding extra characters (usually spaces) around a value to fill a certain width. When using the .format() method or f-strings, you can specify padding by including a width number after the colon : in the placeholder. Python will add spaces to the left or right to make up the difference if the value is shorter than the specified width. You can also control the alignment (left, right, or center) and the padding character.

Syntax

formatted_string = “{:pad_char>width}”.format(value) # Right padding
formatted_string = “{:pad_char<width}”.format(value) # Left padding

Explanation

  • formatted_string: Variable will store the formatted string with padding.
  • "{:pad_char>width}" or "{:pad_char<width}": String templates with placeholders that specify padding.
  • pad_char: Character used for padding (optional, defaults to space).
  • >: Right aligns the value within the available space.
  • <: Left aligns the value within the available space.
  • width: Total width of the field.
  • .format(): Method applies the padding.
  • value: Value to be padded. It is passed as parameter to .format().

Example

text = "Python"
padded_right = "{:_>10}".format(text)  # Pad with underscores on the right
padded_left = "{:.<10}".format(text)  # Pad with dots on the left

print(padded_right)
print(padded_left)

Explanation

  • text = "Python": Initializes a string variable text.
  • padded_right = "{:_>10}".format(text): Formats text to be right-aligned within a width of 10, padded with underscores.
  • padded_left = "{:.<10}".format(text): Formats text to be left-aligned within a width of 10, padded with dots.
  • print(padded_right): Prints the right-padded string.
  • print(padded_left): Prints the left-padded string.

Output

____Python
Python….


Demonstration of Spacing when Strings are Passed as Parameters

When you pass strings as parameters to the .format() method, Python handles spacing based on the placeholders in your template string. If you use empty placeholders {}, the strings are inserted with no extra spaces between them (unless you explicitly include spaces in your template). If you use format specifiers to add padding or alignment, Python will adjust the spacing accordingly, adding spaces (or other padding characters) to meet the specified width.

Syntax

formatted_string = “{} {}”.format(string1, string2)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{} {}": String template with two placeholders.
  • .format(): Method inserts the strings into the placeholders.
  • string1: First string to be inserted. It is passed as first parameter to .format().
  • string2: Second string to be inserted. It is passed as second parameter to .format().

Example

first_name = "John"
last_name = "Doe"
full_name = "{} {}".format(first_name, last_name)
print(full_name)

Explanation

  • first_name = "John": Initializes a string variable first_name.
  • last_name = "Doe": Initializes a string variable last_name.
  • full_name = "{} {}".format(first_name, last_name): Formats the string by inserting first_name and last_name into the placeholders, separated by a space.
  • print(full_name): Prints the formatted string.

Output

John Doe


Using a Dictionary for String Formatting

You can use a dictionary to provide values for placeholders in a string template when using the Python format() method. This is done by passing the dictionary as keyword arguments using the ** unpacking operator. Inside the template string, you use the dictionary keys as the names of the placeholders. This approach is particularly useful when you have a set of named values you want to insert into a string in a specific format.

Syntax

formatted_string = “{key1} {key2}”.format(**dictionary)

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{key1} {key2}": String template with named placeholders.
  • .format(): Method formats the string using values from the dictionary.
  • **dictionary: Unpacks the dictionary into keyword arguments, where the keys are treated as parameter names. The keys of the dictionary should match the placeholder.

Example

person = {"name": "Alice", "age": "30"}
info = "Name: {name}, Age: {age}".format(**person)
print(info)

Explanation

  • person = {"name": "Alice", "age": "30"}: Initializes a dictionary person with keys “name” and “age”.
  • info = "Name: {name}, Age: {age}".format(**person): Formats the string using the values from the person dictionary, unpacking it into keyword arguments.
  • print(info): Prints the formatted string.

Output

Name: Alice, Age: 30


Python format() with List

You can use a list to provide values for placeholders in a string template when using the Python format() method. You pass the list elements as positional arguments to .format() to do this. Inside the template string, you refer to the list elements by their index (starting from 0) within the curly braces. This is useful when you have a sequence of values to insert into a string in a particular order.

Syntax

formatted_string = “{0} {1} {2}”.format(list[0], list[1], list[2])

Explanation

  • formatted_string: Variable will store the formatted string.
  • "{0} {1} {2}": String template where placeholders are indexed to correspond to list elements.
  • .format(): Method formats the string, taking values from the list.
  • list[0], list[1], list[2]: Elements from the list, used as positional arguments for .format().

Example

my_list = ["apple", "banana", "cherry"]
sentence = "I like {0}, {1}, and {2}.".format(*my_list)
print(sentence)

Explanation

  • my_list = ["apple", "banana", "cherry"]: Initializes a list my_list with three string elements.
  • sentence = "I like {0}, {1}, and {2}.".format(*my_list): Formats the string by inserting list elements into the placeholders by their index. The * is used to unpack the list.
  • print(sentence): Prints the formatted string.

Output

I like apple, banana, and cherry.


Conclusion

Python format() method and f-strings provide a powerful and flexible way to create formatted strings in Python. It allows for precise control over the appearance of strings, including features like padding, alignment, number formatting, and type specifying. While newer techniques like f-strings are often more concise and readable, understanding .format() is valuable for working with older code and for its versatility. Remember that using the incorrect format specifier can cause errors in your code.


Also Read

Python float()

Python frozenset()


Python Reference

python format()

Table of Contents