Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • Python Tutorial
    • Data Types
    • Interview Questions
    • Examples
    • Quizzes
    • DSA Python
    • Data Science
    • NumPy
    • Pandas
    • Practice
    • Django
    • Flask
    • Projects
    Open In App

    Python String format() Method

    Last Updated : 11 Jul, 2025
    Comments
    Improve
    Suggest changes
    134 Likes
    Like
    Report

    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:

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

    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 <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 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:

    • %-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:

    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:

    • {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
    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.

    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.

    Create Quiz

    R

    retr0
    Improve

    R

    retr0
    Improve
    Article Tags :
    • Python
    • Python-Built-in-functions
    • python-string

    Explore

      Python Fundamentals

      Python Introduction

      2 min read

      Input and Output in Python

      4 min read

      Python Variables

      4 min read

      Python Operators

      4 min read

      Python Keywords

      2 min read

      Python Data Types

      8 min read

      Conditional Statements in Python

      3 min read

      Loops in Python - For, While and Nested Loops

      5 min read

      Python Functions

      5 min read

      Recursion in Python

      4 min read

      Python Lambda Functions

      5 min read

      Python Data Structures

      Python String

      5 min read

      Python Lists

      4 min read

      Python Tuples

      4 min read

      Python Dictionary

      3 min read

      Python Sets

      6 min read

      Python Arrays

      7 min read

      List Comprehension in Python

      4 min read

      Advanced Python

      Python OOP Concepts

      11 min read

      Python Exception Handling

      5 min read

      File Handling in Python

      4 min read

      Python Database Tutorial

      4 min read

      Python MongoDB Tutorial

      3 min read

      Python MySQL

      9 min read

      Python Packages

      10 min read

      Python Modules

      3 min read

      Python DSA Libraries

      15 min read

      List of Python GUI Library and Packages

      3 min read

      Data Science with Python

      NumPy Tutorial - Python Library

      3 min read

      Pandas Tutorial

      4 min read

      Matplotlib Tutorial

      5 min read

      Python Seaborn Tutorial

      3 min read

      StatsModel Library - Tutorial

      3 min read

      Learning Model Building in Scikit-learn

      6 min read

      TensorFlow Tutorial

      2 min read

      PyTorch Tutorial

      6 min read

      Web Development with Python

      Flask Tutorial

      8 min read

      Django Tutorial | Learn Django Framework

      7 min read

      Django ORM - Inserting, Updating & Deleting Data

      4 min read

      Templating With Jinja2 in Flask

      6 min read

      Django Templates

      5 min read

      Build a REST API using Flask - Python

      3 min read

      Building a Simple API with Django REST Framework

      3 min read

      Python Practice

      Python Quiz

      1 min read

      Python Coding Practice

      1 min read

      Python Interview Questions and Answers

      15+ min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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.
See More

What kind of Experience do you want to share?

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