Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
f-strings in Python
Next article icon

format() method inPython is a tool used to create formattedstrings. By embeddingvariables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolationmore readable and efficient. Example:

Python
a="shakshi"# nameb=22# agemsg="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

Asingle 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 placeholderprint("{}, a platform for coding enthusiasts.".format("GeeksforGeeks"))# formatting with a variablea="Python"print("This article is written in{}.".format(a))# formatting with a numberb=18print("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 usemultiple 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:

Python
# Using multiple placeholdersprint("{} is a{} science portal for{}.".format("GeeksforGeeks","computer","geeks"))# Formatting different data typesprint("Hi! My name is{} and I am{} years old.".format("User",19))# Values replace placeholders in orderprint("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 <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 sequenceDescription     Example      
\nBreaks the string into a new lineprint('I designed this rhyme to explain in due time\nAll I know')
\tAdds a horizontal tabprint('Time is a \tvaluable thing')
\\Prints a backslashprint('Watch it fly by\\as the pendulum swings')
\'   Prints a single quoteprint('It doesn\'t even matter how hard you try')
\"    Prints a double quoteprint('It is so\"unreal\"')
\amakes a sound like a bellprint('\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:

Python
# Positional arguments (placed in order)print("{} love{}!!".format("GeeksforGeeks","Geeks"))# Changing order using indexprint("{1} love{0}!!".format("GeeksforGeeks","Geeks"))# Default order in placeholdersprint("Every{} should know the use of{}{} programming and{}".format("programmer","Open","Source","Operating Systems"))# Reordering using indexprint("Every{3} should know the use of{2}{1} programming and{0}".format("programmer","Open","Source","Operating Systems"))# keyword argumentsprint("{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 SystemsEvery 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:

  • %-20sleft-aligns the brand name within 20 spaces.
  • %s inserts strings dynamically.
  • %dformats integers properly.
  • %.5truncates 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:

Python
print("This site is{:.6f}% securely{}!!".format(100,"encrypted"))# To limit the precisionprint("My average of this{} was{:.2f}%".format("semester",78.234876))# For no decimal placesprint("My average of this{} was{:.0f}%".format("semester",78.234876))# Convert an integer to its binary or other basesprint("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 1100100The 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:

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
defformatted_table(a,b):foriinrange(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 adictionary 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 dictionaryd, 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 formatb=['{:.2f}'.format(elem)forelemina]print(b)

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

Explanation: list comprehension rounds each element ina to two decimal places, creating a list of formatted strings inb.


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp