Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Format Function in Python

Last Updated on June 30, 2023 by Mayank Dham

The format() function in Python is a powerful tool for string formatting and manipulation. It allows you to create dynamic, customized strings by inserting values into predefined placeholders within a template. With the format() function, you can control the appearance and structure of your output, making it a versatile tool for generating formatted text, constructing complex messages, or presenting data in a readable and professional manner.

In this article, we will explore the functionality and usage of the format() function in Python. We will dive into the syntax, placeholders, and various techniques to effectively utilize this function in your code. By understanding how to use the format() function, you will be able to format your strings with precision, flexibility, and ease.

What is the Format Function in Python?

The format() function in Python is a built-in method that allows you to format strings with dynamic values. It provides a flexible and efficient way to construct strings by replacing placeholders within a template string with actual values. This allows you to create output that is customized, readable, and visually appealing.

Syntax of Format Function in Python

Below is the syntax of the format function in Python.

format(value, format_spec)

Parameter of Format Function in Python

There are two parameters in the format function.

  • Value: As the name suggests here we enter the value that has to be formatted the value can be a string or a number.
  • Format_spec: this is optional, if not present then the value will be converted into the string. But when present there is a certain format that needs to be present for format specification

    Format: [[fill]align][sign][#][0][width][,][.precision][type]

The square brackets specifies the field is optional.

This might look difficult but below is the explanation of the format after reading that it will be a lot easier to understand.

  • fill:
    After formatting, it is a character that fills up the blank spaces. Another name for it is a padding character.

  • align:
    The alignment of the output string can be specified as an option.
    "" denotes left alignment
    ">" denotes right alignment,
    "" denotes centre alignment
    "=" denotes justified alignment

  • sign:
    This defines whether or not output will utilise signs.
    "+": Positive numbers are denoted by a "+" while negative numbers are denoted by a "-".

"-": A "-" sign denotes a negative number.

Positive numbers are preceded by a space, whereas negative numbers are indicated by the symbol "-".

  • "#"
    Indicates that a type indicator for numbers should be included in the return value. Hexadecimal numerals, for instance, need to have the "0x" prefix appended.

  • "0"
    This indicates that the output should be consistent and sign-aware, with padding of 0s.

  • width
    Defines the return value’s whole width.

  • ","
    Indicates that commas should be used as a thousand separator in the return value.

  • .precision
    Determines how many characters are added after the decimal point.

  • type
    This specifies the output type. There are three different types:

    • String: To specify a string, use an "s" or nothing at all.
    • Decimal: d; binary: b; octal: o; hexadecimal with lowercase characters: x; uppercase hexadecimal: X; integer: d; (character)
    • Floating point: f (lowercase fixed point), F (uppercase fixed point), E (exponent using "E" as separator), G (lowercase general format), G (uppercase general format), and % (percentage)

Return Type of Format Function in Python

The format function in python will return the value according to the value specified in the format specifiers.

Example 1 of Format Function in Python: Number Formatting

In this example we will see number conversion from one form to another.

val = 22  
print("Original Value (Decimal):")
print(val)


# Octal value
print("Octal value:")
print(format(22, "o"))  

# Binary value
print("Binary value:") 
print(format(22, "b"))  



# Hexadecimal value
print("Hexadecimal value:")
print(format(22, "x"))  

Output

Original Value (Decimal):
22
Octal value:
26
Binary value:
10110
Hexadecimal value:
16

Explanation of the above code
In the above code we have a decimal value of 22 and we have converted that value into octal, binary and hexadecimal.

Example 2 of Format Function in Python: Fill, Width, Align, Sign, Type, Precision.

In this example, we will discuss the example using a format specifier with the syntax explained above.

# Formatting an Integer

print(format(2209, "*>+7,d"))
# Formatting a Floating point number

print(format(153.4756, "^-09.3f"))

Output

*+2,209
0153.4760

Explanation of the above code
In the above example we have specified the format specifier in two scenarios where we are first formatting an integer type number and second type a floating type number.

Example 3 of Format Function in Python: overridingformat()

We will see the overridden format function in python.

class Phone:
    def __format__(self, format):
        if(format == 'colour'):
            return 'Black'
        return 'None'

print(format(Phone(), "colour"))

Output

Black

Explanation of the above code
In the above code we have used the format function in python but have overridden it in the class phone and will return black if the given color is black otherwise it will return none.

String Format Function in Python

There may be several occasions when we need to enter values into a string; in these cases, the str.format() technique is employed.

We may format the provided values and insert them in the spaces of placeholders in the string using Python’s str.format() function.

Using curly brackets "," the placeholders in the str.format() function are specified. In the section below titled "Formatters utilizing Positional and Keyword Arguments,".

Syntax of String Format Function in Python

The syntax of the string format function in python is different from the syntax of the format function in python.

str.format(value1, value2,...)

Here you must have one or more than one parameters.

Parameters of String Format Function in Python

One or more arguments may be sent to the str.format() function; each parameter’s values must be formatted before being added to the input string.

Any data type can be used for the values. A key-value list, a list of values that are separated by commas, or both can be used as parameters.

There are two different sorts of string formatting use cases: single formatters, which are used when we only need to format or insert one value into the string, and multiple formatters, which are used when we need to deal with several values.

Single Formatter

The single formatter is used to insert a single value into a string. The % operator is used to specify the position and type of the value to be inserted, followed by the value itself. Here is an example of a single formatter.

print("My Name is {}".format("Naman"))

Output

My Name is Namaan

Explanation of the above example
In the above example we have used a single formatter and used format function just placed its value in the empty space of the placeholder.

Multiple Formatter

The multiple formatter is used to insert multiple values into a string. The format() method is used to specify the position and type of the values to be inserted, followed by the values themselves. Here is an example of the multiple formatter.

my_string = "My Name is {} and i am {} years {}"
print(my_string.format("Naman", "21", "old"))

Output

My Name is Naman and i am 21 years old

Explanation of the above code
In the above example we have put the various values in the string.

Formatters using Positional and Keyword Arguments

The majority of the values in the str.format() function are of the tuple data type, which is a collection of immutable Python objects. Each value in the tuple is identified by its index, which starts at 0. The placeholders subsequently get these index numbers, which are then replaced with the values.
In Python, the format() function is used for string formatting. This function allows you to insert values into a string in a specified format. The format() function can take both positional and keyword arguments.

Positional Arguments

Positional arguments are specified using curly braces {} as placeholders in the string. The order of the placeholders in the string determines the position of the values in the tuple or list of arguments passed to the format() function. Positional arguments are useful when you know the exact order of the values to be inserted. An example of positional arguments is shown below.

my_string = "Most people loves {0} with {1} and {2}."
print(my_string.format("Burger", "Ketchup", "Fries"))

Output

Most people loves Burger with Ketchup and Fries.

Explanation of the above example
In the above example we have used the index number to get the position in the string placeholder.

Keyword Arguments

Keyword arguments are specified using curly braces with the name of the argument as the placeholder. The key can be any valid Python identifier. Keyword arguments are useful when you want to insert values into a string based on their names, and not their positions. An example of Keyword arguments is shown below:

my_string = "Most people loves {food1} with {food2} and {food3}."
print(my_string.format(food1="Burger", food2="Ketchup", food3="Fries"))

Output

Most people loves Burger with Ketchup and Fries.

Explanation of the above example
Here instead of an index we are using keys to get the values in the placeholder of the string.

Keyword and Positional Argument Combined

We can also use them combined as shown in the example below.

my_string = "Most people loves {0}  and {food1}."
print(my_string.format("Fries", food1="Burger"))

Output

Most people loves Fries  and Burger.

Explanation of the above code
In the above code we have used both positional and keywords, i.e, both indexes and keys.

Type Specification in Format Function in Python

The format code syntax allows for the enclosing of additional parameters in addition to the index or key between curly brackets (placeholders). Here, we will cover how to convert the data type of values into the string format. These parameters are used for converting data type, spacing, or aligning ().

Character Conversion
s strings
d Decimal Integers
f float
c character
b binary
o octal
x hexadecimal
e exponent notation

Example of Type Specification of Format Function in Python

Here we will look at code and implementation of the above-mentioned example.

my_string = "{:d} in binary = {:b}"
print(my_string.format(42, 42))

Output

42 in binary = 101010

Explanation of the above example
In the above example we have converted a decimal number into its corresponding binary number.

Conclusion
One kind of the Python format function deals with strings, and the other type deals with converting values between each other. Both of these types have been thoroughly examined and described. After using the format function in both single and multiple formatters and seeing numerous examples of each kind, we turned our attention to the keyword and positional arguments used in the format function in Python.

Frequently Asked Questions Related to Format Function in Python

Q1: What are placeholders in the format() function?
A1: Placeholders are positions within the template string where values will be inserted. They are represented by curly braces {}. For example, in the template string "Hello, {}!", {} is a placeholder that can be replaced with a value.

Q2: Can I specify the order of the placeholders and values in the format() function?
A2: Yes, by default, the placeholders and values are matched in the order they appear. However, you can also specify the order explicitly by using positional arguments or by indexing the values within the format() function.

Q3: How can I format numbers using the format() function?
A3: The format() function provides various formatting options for numbers, such as specifying decimal precision, adding thousand separators, controlling sign display, and more. These formatting options can be specified within the placeholder. For example, "{:.2f}".format(3.14159) formats the number as a floating-point value with 2 decimal places.

Q4: Can I use named placeholders with the format() function?
A4: Yes, you can use named placeholders to improve readability and make your code more expressive. Instead of using {} as placeholders, you can use names like {name}, {age}, etc. Then, you can pass the values as keyword arguments to the format() function. For example, "My name is {name}. I’m {age} years old.".format(name="Alice", age=30)`.

Leave a Reply

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