:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a:not([href]){color:inherit;text-decoration:none}.markdown-body .absent{color:var(--color-danger-fg)}.markdown-body .anchor{float:left;margin-left:-20px;padding-right:4px;line-height:1}.markdown-body .anchor:focus{outline:none}.markdown-body p,.markdown-body blockquote,.markdown-body ul,.markdown-body ol,.markdown-body dl,.markdown-body table,.markdown-body pre,.markdown-body details{margin-top:0;margin-bottom:16px}.markdown-body hr{height:.25em;background-color:var(--color-border-default);border:0;margin:24px 0;padding:0}.markdown-body blockquote{color:var(--color-fg-muted);border-left:.25em solid var(--color-border-default);padding:0 1em}.markdown-body blockquote>:first-child{margin-top:0}.markdown-body blockquote>:last-child{margin-bottom:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{font-weight:var(--base-text-weight-semibold,600);margin-top:24px;margin-bottom:16px;line-height:1.25}.markdown-body h1 .octicon-link,.markdown-body h2 .octicon-link,.markdown-body h3 .octicon-link,.markdown-body h4 .octicon-link,.markdown-body h5 .octicon-link,.markdown-body h6 .octicon-link{color:var(--color-fg-default);vertical-align:middle;visibility:hidden}.markdown-body h1:hover .anchor,.markdown-body h2:hover .anchor,.markdown-body h3:hover .anchor,.markdown-body h4:hover .anchor,.markdown-body h5:hover .anchor,.markdown-body h6:hover .anchor{text-decoration:none}.markdown-body h1:hover .anchor .octicon-link,.markdown-body h2:hover .anchor .octicon-link,.markdown-body h3:hover .anchor .octicon-link,.markdown-body h4:hover .anchor .octicon-link,.markdown-body h5:hover .anchor .octicon-link,.markdown-body h6:hover .anchor .octicon-link{visibility:visible}.markdown-body h1 tt,.markdown-body h1 code,.markdown-body h2 tt,.markdown-body h2 code,.markdown-body h3 tt,.markdown-body h3 code,.markdown-body h4 tt,.markdown-body h4 code,.markdown-body h5 tt,.markdown-body h5 code,.markdown-body h6 tt,.markdown-body h6 code{font-size:inherit;padding:0 .2em}.markdown-body h1{border-bottom:1px solid var(--color-border-muted);padding-bottom:.3em;font-size:2em}.markdown-body h2{border-bottom:1px solid var(--color-border-muted);padding-bottom:.3em;font-size:1.5em}.markdown-body h3{font-size:1.25em}.markdown-body h4{font-size:1em}.markdown-body h5{font-size:.875em}.markdown-body h6{color:var(--color-fg-muted);font-size:.85em}.markdown-body summary h1,.markdown-body summary h2,.markdown-body summary h3,.markdown-body summary h4,.markdown-body summary h5,.markdown-body summary h6{display:inline-block}.markdown-body summary h1 .anchor,.markdown-body summary h2 .anchor,.markdown-body summary h3 .anchor,.markdown-body summary h4 .anchor,.markdown-body summary h5 .anchor,.markdown-body summary h6 .anchor{margin-left:-40px}.markdown-body summary h1,.markdown-body summary h2{border-bottom:0;padding-bottom:0}.markdown-body ul,.markdown-body ol{padding-left:2em}.markdown-body ul.no-list,.markdown-body ol.no-list{padding:0;list-style-type:none}.markdown-body ol[type=a]{list-style-type:lower-alpha}.markdown-body ol[type=A]{list-style-type:upper-alpha}.markdown-body ol[type=i]{list-style-type:lower-roman}.markdown-body ol[type=I]{list-style-type:upper-roman}.markdown-body ol[type="1"]{list-style-type:decimal}.markdown-body div>ol:not([type]){list-style-type:decimal}.markdown-body ul ul,.markdown-body ul ol,.markdown-body ol ol,.markdown-body ol ul{margin-top:0;margin-bottom:0}.markdown-body li>p{margin-top:16px}.markdown-body li+li{margin-top:.25em}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:1em;font-style:italic;font-weight:var(--base-text-weight-semibold,600);margin-top:16px;padding:0}.markdown-body dl dd{margin-bottom:16px;padding:0 16px}.markdown-body table{width:100%;width:-webkit-max-content;width:-webkit-max-content;width:max-content;max-width:100%;display:block;overflow:auto}.markdown-body table th{font-weight:var(--base-text-weight-semibold,600)}.markdown-body table th,.markdown-body table td{border:1px solid var(--color-border-default);padding:6px 13px}.markdown-body table td>:last-child{margin-bottom:0}.markdown-body table tr{background-color:var(--color-canvas-default);border-top:1px solid var(--color-border-muted)}.markdown-body table tr:nth-child(2n){background-color:var(--color-canvas-subtle)}.markdown-body table img{background-color:transparent}.markdown-body img{max-width:100%;box-sizing:content-box;background-color:var(--color-canvas-default)}.markdown-body img[align=right]{padding-left:20px}.markdown-body img[align=left]{padding-right:20px}.markdown-body .emoji{max-width:none;vertical-align:text-top;background-color:transparent}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{float:left;width:auto;border:1px solid var(--color-border-default);margin:13px 0 0;padding:7px;display:block;overflow:hidden}.markdown-body span.frame span img{float:left;display:block}.markdown-body span.frame span span{clear:both;color:var(--color-fg-default);padding:5px 0 0;display:block}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{text-align:center;margin:13px auto 0;display:block;overflow:hidden}.markdown-body span.align-center span img{text-align:center;margin:0 auto}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{text-align:right;margin:13px 0 0;display:block;overflow:hidden}.markdown-body span.align-right span img{text-align:right;margin:0}.markdown-body span.float-left{float:left;margin-right:13px;display:block;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{float:right;margin-left:13px;display:block;overflow:hidden}.markdown-body span.float-right>span{text-align:right;margin:13px auto 0;display:block;overflow:hidden}.markdown-body code,.markdown-body tt{white-space:break-spaces;background-color:var(--color-neutral-muted);border-radius:6px;margin:0;padding:.2em .4em;font-size:85%}.markdown-body code br,.markdown-body tt br{display:none}.markdown-body del code{-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}.markdown-body samp{font-size:85%}.markdown-body pre{word-wrap:normal}.markdown-body pre code{font-size:100%}.markdown-body pre>code{word-break:normal;white-space:pre;background:0 0;border:0;margin:0;padding:0}.markdown-body .highlight{margin-bottom:16px}.markdown-body .highlight pre{word-break:normal;margin-bottom:0}.markdown-body .highlight pre,.markdown-body pre{background-color:var(--color-canvas-subtle);border-radius:6px;padding:16px;font-size:85%;line-height:1.45;overflow:auto}.markdown-body pre code,.markdown-body pre tt{max-width:auto;line-height:inherit;word-wrap:normal;background-color:transparent;border:0;margin:0;padding:0;display:inline;overflow:visible}.markdown-body .csv-data td,.markdown-body .csv-data th{text-align:left;white-space:nowrap;padding:5px;font-size:12px;line-height:1;overflow:hidden}.markdown-body .csv-data .blob-num{text-align:right;background:var(--color-canvas-default);border:0;padding:10px 8px 9px}.markdown-body .csv-data tr{border-top:0}.markdown-body .csv-data th{font-weight:var(--base-text-weight-semibold,600);background:var(--color-canvas-subtle);border-top:0}.markdown-body [data-footnote-ref]:before{content:"["}.markdown-body [data-footnote-ref]:after{content:"]"}.markdown-body .footnotes{color:var(--color-fg-muted);border-top:1px solid var(--color-border-default);font-size:12px}.markdown-body .footnotes ol{padding-left:16px}.markdown-body .footnotes ol ul{margin-top:16px;padding-left:16px;display:inline-block}.markdown-body .footnotes li{position:relative}.markdown-body .footnotes li:target:before{pointer-events:none;content:"";border:2px solid var(--color-accent-emphasis);border-radius:6px;position:absolute;top:-8px;bottom:-8px;left:-24px;right:-8px}.markdown-body .footnotes li:target{color:var(--color-fg-default)}.markdown-body .footnotes .data-footnote-backref g-emoji{font-family:monospace}.markdown-body{background-color:var(--color-canvas-default);color:var(--color-fg-default)}.markdown-body a{color:var(--color-accent-fg);text-decoration:none}.markdown-body a:hover{text-decoration:underline}.markdown-body img[align=center]{margin:0 auto}.markdown-body iframe{background-color:#fff;border:0;margin-bottom:16px}.markdown-body svg.octicon{fill:currentColor}.markdown-body .anchor>.octicon{display:inline}.markdown-body figcaption{text-align:center;padding-top:2px}.markdown-body .highlight .token.keyword,.gfm-highlight .token.keyword{color:var(--color-prettylights-syntax-keyword)}.markdown-body .highlight .token.tag .token.class-name,.markdown-body .highlight .token.tag .token.script .token.punctuation,.gfm-highlight .token.tag .token.class-name,.gfm-highlight .token.tag .token.script .token.punctuation{color:var(--color-prettylights-syntax-storage-modifier-import)}.markdown-body .highlight .token.operator,.markdown-body .highlight .token.number,.markdown-body .highlight .token.boolean,.markdown-body .highlight .token.tag .token.punctuation,.markdown-body .highlight .token.tag .token.script .token.script-punctuation,.markdown-body .highlight .token.tag .token.attr-name,.gfm-highlight .token.operator,.gfm-highlight .token.number,.gfm-highlight .token.boolean,.gfm-highlight .token.tag .token.punctuation,.gfm-highlight .token.tag .token.script .token.script-punctuation,.gfm-highlight .token.tag .token.attr-name{color:var(--color-prettylights-syntax-constant)}.markdown-body .highlight .token.function,.gfm-highlight .token.function{color:var(--color-prettylights-syntax-entity)}.markdown-body .highlight .token.string,.gfm-highlight .token.string{color:var(--color-prettylights-syntax-string)}.markdown-body .highlight .token.comment,.gfm-highlight .token.comment{color:var(--color-prettylights-syntax-comment)}.markdown-body .highlight .token.class-name,.gfm-highlight .token.class-name{color:var(--color-prettylights-syntax-variable)}.markdown-body .highlight .token.regex,.gfm-highlight .token.regex{color:var(--color-prettylights-syntax-string)}.markdown-body .highlight .token.regex .regex-delimiter,.gfm-highlight .token.regex .regex-delimiter{color:var(--color-prettylights-syntax-constant)}.markdown-body .highlight .token.tag .token.tag,.markdown-body .highlight .token.property,.gfm-highlight .token.tag .token.tag,.gfm-highlight .token.property{color:var(--color-prettylights-syntax-entity-tag)}.markdown-body .highlight .token.deleted,.gfm-highlight .token.deleted{color:var(--color-prettylights-syntax-markup-deleted-text);background-color:var(--color-prettylights-syntax-markup-deleted-bg)}.markdown-body .highlight .token.inserted,.gfm-highlight .token.inserted{color:var(--color-prettylights-syntax-markup-inserted-text);background-color:var(--color-prettylights-syntax-markup-inserted-bg)}

Python String format() Method (original) (raw)

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:

Python `

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.

**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.

Python `

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:

**Note: The number of placeholders must match the number of values provided.

**Example:

Python `

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:

Python `

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
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 sequence Description Example
\n Breaks the string into a new line print(‘I designed this rhyme to explain in due time\nAll I know’)
\t Adds a horizontal tab print(‘Time is a \tvaluable thing’)
\\ Prints a backslash print(‘Watch it fly by\\as the pendulum swings’)
\’ Prints a single quote print(‘It doesn\’t even matter how hard you try’)
\” Prints a double quote print(‘It is so\”unreal\”‘)
\a makes a sound like 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)

**Example:

Python `

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:

Python `

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:

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:

Python `

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

To limit the precision

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

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:

Type Specifying Errors

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

**Example:

Python `

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

Python `

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

Python `

def formatted_table(a, b): for i in range(a, b): print("{:6d} {:6d} {:6d} {:6d}".format(i, i2, i3, 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.

Python `

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.

Python `

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.