0% found this document useful (0 votes)
1 views15 pages

Python String Format() Method - GeeksforGeeks

Uploaded by

Ntsiuoa Tatolo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views15 pages

Python String Format() Method - GeeksforGeeks

Uploaded by

Ntsiuoa Tatolo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python String format() Method

Last Updated : 26 Mar, 2025

format() method in Python is a tool used to create formatted strings. By


embedding variables or values into placeholders within a template string, we can
construct dynamic, well-organized output. It replaces the outdated % formatting
method, making string interpolation more readable and efficient. Example:

a = "shakshi" # name
b = 22 # age

msg = "My name is {0} and I am {1} years old.".format(a,b)


print(msg)

Output

My name is shakshi and I am 22 years old.

Explanation: format(a, b) method replaces {0} with the first argument (a =


"shakshi") and {1} with the second argument (b = 22).

String Format() Syntax


string.format(value1, value2, ...)

Parameter: values (such as integers, strings, or variables) to be inserted into


the placeholders in the string.
Earn $5 per answer
Make money from answering simple
questions. We pay you in cash. Simple
and fun.

MetroOpinion

Open

Returns: a string with the provided values embedded in the placeholders.

Using a single placeholder


A single placeholder {} is used when only one value needs to be inserted into
the string. The format() method replaces the placeholder with the specified
value.

# using a single placeholder


print("{}, a platform for coding
enthusiasts.".format("GeeksforGeeks"))

# formatting with a variable


a = "Python"
print("This article is written in {}.".format(a))

# formatting with a number


b = 18
print("Hello, I am {} years old!".format(b))

Output
GeeksforGeeks, a platform for coding enthusiasts.
This article is written in Python.
Hello, I am 18 years old!

Using multiple placeholders


When a string requires multiple values to be inserted, we use multiple
placeholders {}. The format() method replaces each placeholder with the
corresponding value in the provided order.

Syntax:

"{ } { }".format(value1, value2)

Parameters:

Accepts integers, floats, strings, characters, or variables.

Note: The number of placeholders must match the number of values


provided.

Example:
# Using multiple placeholders
print("{} is a {} science portal for
{}.".format("GeeksforGeeks", "computer", "geeks"))

# Formatting different data types


print("Hi! My name is {} and I am {} years
old.".format("User", 19))

# Values replace placeholders in order


print("This is {} {} {} {}.".format("one", "two", "three",
"four"))

Output

GeeksforGeeks is a computer science portal for geeks.


Hi! My name is User and I am 19 years old.
This is one two three four.

String format() IndexError


Python assigns indexes to placeholders {0}, {1}, {2}, .... If the number of
placeholders exceeds the provided values, an IndexError occurs.

Example:

s = "{}, is a {} {} science portal for {}"


print(s.format("GeeksforGeeks", "computer", "geeks")) #
Missing one argument

Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 2, in
<module>
print(s.format("GeeksforGeeks", "computer", "geeks")) #
Missing one argument
~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
IndexError: Replacement index 3 out of range for positional
args tuple

Escape Sequences in Strings


We can use escape sequences to format strings in a more readable way.
Escape sequences allow us to insert special characters such as newline \n, tab
\t, or quotes.

Escape Description Example


sequence

Breaks the string print('I designed this rhyme to explain


\n
into a new line in due time\nAll I know')

Adds a horizontal
\t print('Time is a \tvaluable thing')
tab

print('Watch it fly by\\as the pendulum


\\ Prints a backslash
swings')

Prints a single print('It doesn\'t even matter how hard


\'
quote you try')

Prints a double
\" print('It is so\"unreal\"')
Prints a double
\" print('It is so\"unreal\"')
quote

makes a sound like

\a a bell print('\a')

Positional and Keyword Arguments in format


In Python, {} placeholders in str.format() are replaced sequentially by default.
However, they can also be explicitly referenced using index numbers (starting
from 0) or keyword arguments.

Syntax:

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

Parameters : (positional_argument, keyword_argument)

Positional_argument can be integers, floating point numeric constants,


strings, characters and even variables.
Keyword_argument is essentially a variable storing some value, which is
passed as parameter.

Example:
# Positional arguments (placed in order)
print("{} love {}!!".format("GeeksforGeeks", "Geeks"))

# Changing order using index


print("{1} love {0}!!".format("GeeksforGeeks", "Geeks"))

# Default order in placeholders


print("Every {} should know the use of {} {} programming
and {}".format("programmer", "Open", "Source", "Operating
Systems"))

# Reordering using index


print("Every {3} should know the use of {2} {1}
programming and {0}".format("programmer", "Open",
"Source", "Operating Systems"))

# keyword arguments
print("{gfg} is a {0} science portal for
{1}".format("computer", "geeks", gfg="GeeksforGeeks"))

Output

GeeksforGeeks love Geeks!!


Geeks love GeeksforGeeks!!
Every programmer should know the use of Open Source
programming and Operating Systems
Every Operating Systems should know the use of Source Open
p...

Formatting with Type Specifiers


Python allows specifying the type specifier while formatting data, such as
integers, floating-point numbers, and strings. This is useful for controlling the
display of numeric values, dates and text alignment.

Example:

product, brand, price, issue, effect = "Smartphone",


"Amazon", 12000, "bug", "troubling"

print("{:<20} is a popular electronics


brand.".format(brand))
print("They have a {} for {} rupees.".format(product,
price))
print("I wondered why the program was {} me—turns out it
was a {}.".format(effect, issue))
print("Truncated product name: {:.5}".format(product))

Output

Amazon is a popular electronics brand.


They have a Smartphone for 12000 rupees.
I wondered why the program was troubling me—turns out it was
a bug.
Truncated product name: Smart

Explanation:
%-20s left-aligns the brand name within 20 spaces.
%s inserts strings dynamically.
%d formats integers properly.
%.5 truncates the product name to the first 5 characters.

Another useful Type Specifying

Specifier Description

%u
unsigned decimal integer

%o
octal integer

%f
floating-point display

%b
binary number

%x
hexadecimal lowercase

%X
hexadecimal uppercase

%e
exponent notation

We can specify formatting symbols using a colon (:) instead of %. For example,
instead of %s, use {:s}, and instead of %d, use {:d}. This approach provides a
more readable and flexible way to format strings in Python.
Example:

print("This site is {:.6f}% securely {}!!".format(100,


"encrypted"))

# To limit the precision


print("My average of this {} was
Python Tutorial Interview Questions Python
{:.2f}%".format("semester", Quiz Python Glossary
78.234876)) Python Projects

# For no decimal places


print("My average of this {} was
{:.0f}%".format("semester", 78.234876))

# Convert an integer to its binary or other bases


print("The {} of 100 is {:b}".format("binary", 100))
print("The {} of 100 is {:o}".format("octal", 100))

Output

This site is 100.000000% securely encrypted!!


My average of this semester was 78.23%
My average of this semester was 78%
The binary of 100 is 1100100
The octal of 100 is 144

Explanation:

{0:f}: Floating-point representation.
{1:.2f}: Floating-point with two decimal places.
{1:.0f}: Rounds the floating number to the nearest integer.
{1:b}: Converts integer to binary.
{1:o}: Converts integer to octal.

Type Specifying Errors


When explicitly converted floating-point values to decimal with base-10 by 'd'
type conversion we encounter Value-Error.

Example:

print("The temperature today is {:d} degrees outside


!".format(35.567))

Output

ValueError: Unknown format code 'd' for object of type


'float'

# Instead write this to avoid value-errors

print("The temperature today is {:.0f} degrees outside


!".format(35.567))

Output

The temperature today is 36 degrees outside !

Handling large data with formatting


Formatters are generally used to Organize Data. If we are showing databases to
users, using formatters to increase field size and modify alignment can make the
output more readable.
Example: Organizing numerical data

def formatted_table(a, b):


for i in range(a, b):
print("{:6d} {:6d} {:6d} {:6d}".format(i, i**2,
i**3, i**4))

formatted_table(3, 10)

Output

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

Explanation: The formatted_table function prints a table of numbers from a to


b-1, displaying each number along with its square, cube, and fourth power. It
formats the output with each value taking up 6 spaces for clean alignment.

Using a dictionary for formatting


Using a dictionary to unpack values into the placeholders in the string that needs
to be formatted. We basically use ** to unpack the values. This method can be
useful in string substitution while preparing an SQL query.
d = {"first_name": "Tony", "last_name": "Stark", "aka":
"Iron Man"}
print("My name is {first_name} {last_name}, also known as
{aka}.".format(**d))

Output

My name is Tony Stark, also known as Iron Man.

Explanation: format(**d) method unpacks the dictionary d, replacing the


named placeholders with corresponding values, resulting in a formatted string.

Python format() with list


Given a list of float values, the task is to truncate all float values to 2 decimal
digits. Let’s see the different methods to do the task.

a = [100.7689454, 17.232999, 60.98867, 300.83748789]

# Using format
b = ['{:.2f}'.format(elem) for elem in a]

print(b)

Output

['100.77', '17.23', '60.99', '300.84']

Explanation: list comprehension rounds each element in a to two decimal


places, creating a list of formatted strings in b.
Advertise with us Next Article

R retr0 Follow

133

Similar Reads

Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters,
numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons =
"GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read

Why are Python Strings Immutable?


Strings in Python are "immutable" which means they can not be changed after they are created. Some other
immutable data types are integers, float, boolean, etc. The immutability of Python string is very useful as it
helps in hashing, performance optimization, safety, ease of use, etc. The article wi
5 min read

Python - Modify Strings


Python provides an wide range of built-in methods that make string manipulation simple and efficient. In this
article, we'll explore several techniques for modifying strings in Python.Start with doing a simple string
modification by changing the its case:Changing CaseOne of the simplest ways to modi
3 min read

Python String Manipulations

Iterate over characters of a string in Python


In this article, we will learn how to iterate over the characters of a string in Python. There are several
methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s
explore this approach.Using for loopThe simplest way to iterate over the characters in
2 min read

Python String Concatenation and Comparison


Python String Formatting

Python String Formatting - How to format String?


String formatting allows you to create dynamic strings by combining variables and values. In this article, we
will discuss about 5 ways to format a string.You will learn different methods of string formatting with
examples for better understanding. Let's look at them now!How to Format Strings in Pyt
9 min read

What does %s mean in a Python format string?


In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting
operation. It allows us to insert values dynamically into a string, making our code more flexible and
readable. This placeholder is part of Python's older string formatting method, using the % o
3 min read

Python String Interpolation


String Interpolation is the process of substituting values of variables into placeholders in a string. Let's
consider an example to understand it better, suppose you want to change the value of the string every time
you print the string like you want to print "hello <name> welcome to geeks for
4 min read

Python Modulo String Formatting


In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using
% 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting
using % is similar to that of 'printf' in C programming language. %d - integer %f -
2 min read

How to use String Formatters in Python


In Python, we use string formatting to control how text is displayed. It allows us to insert values into strings
and organize the output in a clear and readable way. In this article, we’ll explore different methods of
formatting strings in Python to make our code more structured and user-friendly.Us
3 min read

Python String format() Method


format() method in Python is a tool used to create formatted strings. By embedding variables or values into
placeholders within a template string, we can construct dynamic, well-organized output. It replaces the
outdated % formatting method, making string interpolation more readable and efficient. E
8 min read

You might also like