Easy way to IT Job

Format Function in Python
Share on your Social Media

Format Function in Python

Published On: July 20, 2022

Format Function in Python

Format function in Python is a popular technique for string manipulation that allows developers Data formatting and it enables you to concatenate strings at the required intervals.

We want to explain to you what is format function along with its uses and how it works in Python through this article.

Enrich your skills at the Best Python Training Institute in Chennai for a bright future.

This blog covers

  • Single Formatter
  • Multiple Formatter
  • String Formatting with Escape Sequences
  • Positional and Keyword Arguments with Formatters
  • Type Specification
  • Alignments and Spacing with Formatter
  • Data Organizing
  • Dictionary Usage for String Formatting

Single Formatter

Single Formatters are used to put one or more replacement fields that are defined by a pair of curly braces {} into a string using the str.format().

The required value for the placeholders will be concatenated with the string passed parameters into this single format function.

Single formatter will be defined when there is a need for only one placeholder.

Syntax: { }.format (value)

Parameters

Value: Single format can include integers, floating point numbers, strings, characters, or variables.

ReturnType: It returns a formatted string with the value passed as a parameter in the field position.

Example

Print(“{} is the best for learning Python”.format(“Softlogic”))

Output

Softlogic is the best for learning Python.

Single formatter can be defined as a variable as follows

Example

sample_string = “{} is the best for learning Python”

print(sample_string.format(“Softlogic”))

Output

Softlogic is the best for learning Python.

Multiple Formatter

Multiple formatters contain more than one curly braces to concatenate strings into a statement.

Here, python replaces the placeholders with the required value that are passed as parameters.

Example

sample_string = “{ } is the best for learning Python in {}”

print(sample_string.format(“Softlogic”, “Chennai”))

Output

Softlogic is the best for learning Python in Chennai

String Formatting with Escape Sequences

In python, we can use two or more specially designated characters within a string for formatting it.

They are known as escape sequences and it will be denoted with backslash ().

Following are the escape sequences used with formatters in Python

n is to break the string into a new line

t is to add a horizontal tab

\ is to print a backslash

’ is to print a single quote

” is to print a double quote

a is to add a sound like a bell

Positional and Keyword Arguments with Formatters in Python

Python can replace the values passed through str.format when the placeholders or fields are empty.

The existing values within the str.format() can be tuple data types and every value of the tuple can be called by its index number that must be started with 0.

Syntax

{0} {1}.format (positional_argument, keyword_argument)

Parameters

A positional Argument can be any data type like integer, floating point, string, character, or a variable

Keyword Argument must be a variable that has some value to be passed as a parameter.

Example

sample_string = “{0} is the best institute for python aspirants in {city}”

print(sample_string.format (“Softlogic”, city = “Chennai”))

Output

Softlogic is the best institute for python aspirants in Chennai.

Type Specification

Using the format code syntax with {field_name:conversion) in Python helps in including more parameters within the curly braces of the syntax.

Here, field_name denotes the index number of the argument str.format() and conversion denotes the conversion code of the data type.

Following are the popularly used conversion types

String – s

Decimal Integers – d

Floating point numbers – f

Character – c

Binary – b

Octal – o

Hexadecimal with lowercase – x

Hexadecimal with uppercase – X

Unsigned decimal integer – u

Exponent Notation – e

%s – String Conversion via str() before the formatting

Example

sample_string = “We are leaving {0} by {1:f} pm tomorrow”

print(sample_string.format(“Chennai”, 12.30))

Output

We are leaving Chennai by 12.30 pm tomorrow.

Alignments and Spacing with Formatter

The format() method can be used to apply spaces and aligning strings to the left or the right or both sides of the placeholder or field.

< : left-align text

^ : center text

> : right-align

Example

sample_string = “We are living in {0:22} and now it is {1} month”

print (sample_string.format(2022,”July”))

Output

We are living in 2022 and now it is July month

The strings can be aligned on both sides as below

sample_string = “We are living in {0:>22} and now it is {1} month”

We are living in 2022 and now it is July Month

Organizing Data in Python

Formatters can be used in applications for organizing data.

If it is required to show the database to the end-user, formatters can be used for increasing the field size and editing the alignment for a better readability.

Example

# which prints out i, i ^ 2, i ^ 3,

# i ^ 4 in the given range

# Function prints out values

# in an unorganized manner

def unorganized(a, b):

for i in range(a, b):

print(i, i**2, i**3, i**4)

# Function prints the organized set of values

def organized(a, b):

for i in range(a, b):

# Using formatters to give 6

# spaces to each set of values

print(“{:6d} {:6d} {:6d} {:6d}”

.format(i, i ** 2, i ** 3, i ** 4))

# Driver Code

n1 = int(input(“Enter lower range :-n”))

n2 = int(input(“Enter upper range :-n”))

print(“——Before Using Formatters——-“)

# Calling function without formatters

unorganized(n1, n2)

print()

print(“——-After Using Formatters———“)

print()

# Calling function that contains

# formatters to organize the data

organized(n1, n2)

Output

Enter lower range :-

3

Enter upper range :-

10

——Before Using Formatters——-

3 9 27 81

4 16 64 256

5 25 125 625

6 36 216 1296

7 49 343 2401

8 64 512 4096

9 81 729 6561

——-After Using Formatters———

3 9 27 81

4 16 64 256

5 25 125 625

6 36 216 1296

7 49 343 2401

  1. 64 512 4096

9 81 729 6561

Dictionary Usage for String Formatting

Dictionaries are used in string formatting in Python to unpack values into the placeholders when they require to be formatted. ** is used to unpack the values and this method is useful while preparing SQL queries for substituting strings.

Example

introduction = ‘My name is {first_name} {middle_name} {last_name} AKA the {aka}.’

full_name = {

‘first_name’: ‘James’,

‘middle_name’: Steward,

‘last_name’: ‘Junior’,

‘aka’: ‘Wonder Man’,

}

# Notice the use of “**” operator to unpack the values.

print(introduction.format(**full_name))

Output

My name is James Steward Junior AKA The Wonder Man

Python Formatting with List

We can truncate float values to 2 decimal digits with the given float values and it can be formatted as below

Example

# Python code to truncate float

# values to 2 decimal digits.

# List initialization

Input = [84.1689454, 21.232999, 50.98867, 123.51748789]

# Using format

Output = [‘{:.2f}’.format(elem) for elem in Input]

# Print output

print(Output)

Output

[‘84.17’, ’21.23’, ’50.99’, ‘123.52’]

Conclusion

We hope this article will help you understand the formatting in Python functions through examples.

Our trainers will equip you with industry-required python skills for developing applications efficiently.

Learn the Best Python Course in Chennai at Softlogic Systems to understand advanced concepts like formatting with the best practices.

We have meticulously prepared the coursework that can be learned from scratch by beginners and personalized by experienced learners.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.