{"id":6901,"date":"2018-11-04T12:06:12","date_gmt":"2018-11-04T06:36:12","guid":{"rendered":"https:\/\/techbeamers.com\/?p=6901"},"modified":"2025-11-30T10:52:44","modified_gmt":"2025-11-30T15:52:44","slug":"python-string-format","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/python-string-format\/","title":{"rendered":"Python String Format()"},"content":{"rendered":"\n<p>String formatting is a basic concept in Python that allows you to modify and display text with ease. For this purpose, Python provides a string format() method which is a versatile and powerful tool for string formatting. In this tutorial, we will delve into this method, and its features, and learn how to use it with examples. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-string-format-method\">Python String Format() Method<\/h2>\n\n\n\n<p>Python&#8217;s<code>str.format()<\/code> method is a newer and more flexible way to format strings in Python. It has been available since Python 3.1 and is now the preferred method for string formatting.<\/p>\n\n\n\n<p>To format a string using the <code>str.format()<\/code> method, you pass it a format string and a set of keyword arguments. The format string contains placeholders for the values, which are replaced when the string formatting happens.<\/p>\n\n\n\n<p>The placeholders in the format string are marked with curly braces ({ }), Inside the curly braces, you can specify the name of the keyword argument that contains the value to replace the placeholder.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-str-format-syntax\">Str.Format() Syntax<\/h3>\n\n\n\n<p>The basic syntax of the method <code>str.format()<\/code> is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">formatted_string = \"Place any text here: {}\".format(value)<\/pre>\n\n\n\n<p>In this syntax:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>\"Place any text here: {}\"<\/code> is the string template where <code>{}<\/code> serves as a placeholder for values.<\/li>\n\n\n\n<li><code>format()<\/code> is the method that formats the string.<\/li>\n\n\n\n<li><code>value<\/code> is the actual value that replaces the placeholder.<\/li>\n<\/ul>\n\n\n\n<p>You can have multiple placeholders within a single string, and you have flexibility in how you provide values to replace them.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-parameters-of-str-format\">Parameters of <code style=\"border: 0px solid rgb(217, 217, 227); box-sizing: border-box; --tw-border-spacing-x:0; --tw-border-spacing-y:0; --tw-translate-x:0; --tw-translate-y:0; --tw-rotate:0; --tw-skew-x:0; --tw-skew-y:0; --tw-scale-x:1; --tw-scale-y:1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness:proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width:0px; --tw-ring-offset-color:#fff; --tw-ring-color:rgba(69,89,164,0.5); --tw-ring-offset-shadow:0 0 transparent; --tw-ring-shadow:0 0 transparent; --tw-shadow:0 0 transparent; --tw-shadow-colored:0 0 transparent; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; font-size: 0.875em; color: inherit; font-family: &quot;S\u00f6hne Mono&quot;, Monaco, &quot;Andale Mono&quot;, &quot;Ubuntu Mono&quot;, monospace !important;\">str.format()<\/code><\/h4>\n\n\n\n<p>Let&#8217;s find out the important parameters used in the <code>str.format()<\/code> method:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Parameter<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>{}<\/code> (Curly Braces)<\/td><td>Placeholders within the string that specify where values should be inserted. Multiple placeholders can be used within a single string.<\/td><\/tr><tr><td><code>format()<\/code> method<\/td><td>The method used to format the string. It should be called on the string containing placeholders.<\/td><\/tr><tr><td><code>value<\/code><\/td><td>The value that replaces a placeholder. It can be a variable, literal, expression, or any valid Python object.<\/td><\/tr><tr><td>Positional Arguments<\/td><td>Values provided to the <code>format()<\/code> method in the order they should replace placeholders. For example: <code>\"{} {}\".format(value1, value2)<\/code>.<\/td><\/tr><tr><td>Named Arguments<\/td><td>Values passed in the <code>format()<\/code> method using names for placeholders. For example: <code>\"Name: {name}, Age: {age}\".format(name=\"Alex\", age=30)<\/code>.<\/td><\/tr><tr><td>Format Specifiers<\/td><td>Optional formatting instructions that follow the placeholders and define how the values should be displayed. For example: <code>\"{:.2f}\".format(3.14159265359)<\/code> specifies formatting a floating-point number with two decimal places.<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">String Format Function Signature <\/figcaption><\/figure>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"589\" height=\"325\" src=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/11\/Format-String-Int-Float-Align-List-Dict-in-Python.png\" alt=\"Format String, Int, Float, Align, List, Dict in Python\" class=\"wp-image-7223\"\/><\/figure>\n<\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-using-python-string-format-for-strings\">Using Python String Format() for Strings<\/h3>\n\n\n\n<p>You can invoke the format function in many of the following ways. <\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-basic-string-formatting\">Basic String Formatting<\/h4>\n\n\n\n<p>Here&#8217;s an example to illustrate how these parameters work together:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">name = \"Alex\"\nage = 30\nheight = 5.8\noutstr = \"Name: {}, Age: {}, Height: {:.2f}\".format(name, age, height)\nprint(outstr)<\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>{}<\/code> are placeholders within the string.<\/li>\n\n\n\n<li><code>format()<\/code> will format the string.<\/li>\n\n\n\n<li><code>name<\/code>, <code>age<\/code>, and <code>height<\/code> are values that replace the placeholders.<\/li>\n\n\n\n<li><code>\"{:.2f}\"<\/code> is a format specifier that formats the <code>height<\/code> variable as a floating-point number with two decimal places.<\/li>\n<\/ul>\n\n\n\n<p>The output will be: <code>Name: Alex, Age: 30, Height: 5.80<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-padding-and-align-strings\">Padding and Align Strings<\/h4>\n\n\n\n<p>Padding and aligning strings is a common requirement when formatting text, and the <code>str.format()<\/code> method provides easy ways to achieve this. Here&#8217;s a detailed example of how to pad and align strings using <code>str.format()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Define some example data\nitem1 = \"Apple\"\nitem2 = \"Banana\"\nitem3 = \"Cherry\"\n\n# Create a template with placeholders and alignment\nformatted_string = \"{:&lt;10} | {:^10} | {:&gt;10}\".format(item1, item2, item3)\n\n# Print the formatted string\nprint(formatted_string)<\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>item1<\/code>, <code>item2<\/code>, and <code>item3<\/code> are three strings representing items.<\/li>\n\n\n\n<li>The template string <code>\"{:&lt;10} | {:^10} | {:&gt;10}\"<\/code> defines the format of the output. It contains three placeholders separated by vertical bars (<code>|<\/code>), each with a different alignment and width:\n<ul class=\"wp-block-list\">\n<li><code>\"{:&lt;10}\"<\/code> aligns the text to the left (<code>&lt;<\/code>) and specifies a width of 10 characters. This means <code>item1<\/code> (Apple) will be left-aligned within a 10-character-wide field.<\/li>\n\n\n\n<li><code>\"{:^10}\"<\/code> aligns the text to the center (<code>^<\/code>) and specifies a width of 10 characters. This centers <code>item2<\/code> (Banana) within a 10-character-wide field.<\/li>\n\n\n\n<li><code>\"{:&gt;10}\"<\/code> aligns the text to the right (<code>&gt;<\/code>) and specifies a width of 10 characters. This right-aligns <code>item3<\/code> (Cherry) within a 10-character-wide field.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p>When you run this code, the output will be:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Apple      |   Banana   |     Cherry<\/pre>\n\n\n\n<p>Also Read: <a href=\"https:\/\/techbeamers.com\/python-string-formatting-methods\/\" target=\"_blank\" rel=\"noreferrer noopener\">Different Python Methods for String Formatting<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-justify-a-variable-string-expansion\">Justify a variable string expansion<\/h4>\n\n\n\n<p>In the below example, we demonstrate&nbsp;the variable string expansion and justify it.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Define a list of items with varying lengths\nitems = [\"Apple\", \"Banana\", \"Cherry\", \"Grapes\", \"Strawberry\"]\n\n# Create a template with a placeholder for variable content and right alignment\ntemplate = \"{:&gt;12}\"\n\n# Print a header\nprint(\"Fruit Names:\")\nprint(\"-\" * 20)\n\n# Iterate through the items and format each one with right alignment\nfor item in items:\n    formatted_item = template.format(item)\n    print(formatted_item)<\/pre>\n\n\n\n<p>In this code:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We have a <a href=\"https:\/\/techbeamers.com\/length-of-a-list-in-python\/\">list of items which have different lengths<\/a>.<\/li>\n\n\n\n<li>The template string <code>\"{:&gt;12}\"<\/code> defines the format for each item. It contains a single placeholder that specifies the right alignment (<code>&gt;<\/code>) with a width of 12 characters. The width ensures equal spacing, even for shorter strings.<\/li>\n\n\n\n<li>We print a header and a line below it for clarity.<\/li>\n<\/ul>\n\n\n\n<p>When you run this code, the output will be:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Fruit Names:\n--------------------\n       Apple\n      Banana\n      Cherry\n      Grapes\n Strawberry<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-using-python-string-format-for-integers\">Using Python String Format for Integers<\/h3>\n\n\n\n<p>There are many ways to format an Integer, let&#8217;s see the basic usage first.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"I've &lt;{}&gt; years of experience and my salary is &lt;{}&gt; USD per annum.\".format(10, 75000))\n\n#I've &lt;10&gt; years of experience and my salary is &lt;75000&gt; USD per annum.<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-separator-number-formatting\">Separator Number Formatting<\/h4>\n\n\n\n<p>It is a standard convention to display the salary with commas. Python string format function supports this representation&nbsp;and requires a pair of &#8216;:&#8217; and &#8216;,&#8217;&nbsp;inside the parenthesis.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"I've &lt;{}&gt; years of experience and my salary is &lt;{:,}&gt; USD per annum.\".format(10, 75000))\n\n#I've &lt;10&gt; years of experience and my salary is &lt;75,000&gt; USD per annum.<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-specify-field-width-for-numbers\">Specify Field Width for Numbers<\/h4>\n\n\n\n<p>The same as we did for strings is applicable for integers. For integers, we can&#8217;t use precision.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"I've &lt;{:5}&gt; years of experience and my salary is &lt;{:15,}&gt; USD per annum.\".format(10, 75000))\n\n#I've &lt;   10&gt; years of experience and my salary is &lt;         75,000&gt; USD per annum.<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-padding-for-numbers\">Padding for Numbers<\/h4>\n\n\n\n<p>While specifying the width for integers, you can use a character for padding the space left vacant after printing the subject.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"I've &lt;{:#&gt;8}&gt; years of experience and my salary is &lt;{:z&gt;20,}&gt; USD per annum.\".format(10, 75000))\n\n#I've &lt;######10&gt; years of experience and my salary is &lt;zzzzzzzzzzzzzz75,000&gt; USD per annum.<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-format-a-number-as-binary\">Format a Number as Binary<\/h4>\n\n\n\n<p>Python format function allows printing a number in binary style. The symbol &#8216;b&#8217; after the colon inside the parenthesis notifies to display a number in binary format.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print('{0:b}'.format(10))\n\n#1010<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-format-a-number-in-octal-style\">Format a Number in Octal Style<\/h4>\n\n\n\n<p>Python format function allows printing&nbsp;an integer&nbsp;in the octal style. The symbol &#8216;o&#8217; after the colon inside the parenthesis notifies to display a number in octal format.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print('{0:o}'.format(10))\n\n#12<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-format-a-number-as-hex\">Format a Number as Hex<\/h4>\n\n\n\n<p>Python format function allows printing an integer in the hex style. The symbol &#8216;x&#8217; or &#8216;X&#8217; after the colon inside the parenthesis notifies to display a number in hex format.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print('{0:x}'.format(10))\n#a\n&gt;&gt;&gt; print('{0:X}'.format(10))\n#A<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-using-python-string-format-for-floats\">Using Python String Format for Floats<\/h3>\n\n\n\n<p>A <a href=\"https:\/\/techbeamers.com\/python-float-function\/\" target=\"_blank\" rel=\"noopener\">float<\/a> data type also has a couple of variations which you can style using the Python format function.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-simple-example\">Simple Example<\/h4>\n\n\n\n<p>Let&#8217;s print a full <a href=\"https:\/\/techbeamers.com\/floating-point-numbers-in-python\/\" target=\"_blank\" rel=\"noopener\">floating point number<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"{0:f}\".format(1.123456))\n\n#1.123456<\/pre>\n\n\n\n<p>Now, let&#8217;s print a floating point number truncating after three decimal points.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"{0:.3f}\".format(1.123456))\n\n#1.123<\/pre>\n\n\n\n<p>Finally, let&#8217;s print a floating point number that truncates after three decimal places but does round the final value.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\"{0:.3f}\".format(1.123556))\n\n#1.124<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-fixed-point\">Fixed Point<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">print('Fixed-point example: &lt;{0:f}&gt;'.format(2.2183))\n#Fixed-point example: &lt;2.218300&gt;\n\nprint('Fixed-point with right alignment example: &lt;{0:25f}&gt;'.format(2.2183))\n#Fixed-point with right alignment example: &lt;                 2.218300&gt;\n\nprint('Fixed-point with precision and right alignment example: &lt;{0:&lt;25.10f}&gt;'.format(2.2183))\n#Fixed-point with precision and right alignment example: &lt;2.2183000000             &gt;<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-general\">General<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">print('General format example: &lt;{0:g}&gt;'.format(2.2183))\n#General format example: &lt;2.2183&gt;\n\nprint('General format with right alignment example: &lt;{0:25g}&gt;'.format(2.2183))\n#General format with right alignment example: &lt;                   2.2183&gt;\n\nprint('General format with precision and center alignment example: &lt;{0:^25.10g}&gt;'.format(2.2183))\n#General format with precision and center alignment example: &lt;         2.2183          &gt;<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-scientific\">Scientific<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">print('Scientific format example: &lt;{0:e}&gt;'.format(2.2183))\n#Scientific format example: &lt;2.218300e+00&gt;\n\nprint('Scientific format with left alignment example: &lt;{0:&lt;25e}&gt;'.format(2.2183))\n#Scientific format with left alignment example: &lt;2.218300e+00             &gt;\n\nprint('General format with precision and right alignment example: &lt;{0:&gt;25.5e}&gt;'.format(2.2183))\n#General format with precision and right alignment example: &lt;              2.21830e+00&gt;<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-format-lists-and-dictionaries\">Format Lists and Dictionaries<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-formatting-list-in-python\">Formatting List in Python<\/h4>\n\n\n\n<p>The Python string format method accepts a sequence of&nbsp;positional parameters. If we pass an array or a List, then let&#8217;s find out the result.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">langs = ['C', 'C++', 'CSharp']\nprint('Skillset: {}'.format(langs))\n\n#Skillset: ['C', 'C++', 'CSharp']<\/pre>\n\n\n\n<p>The whole list is displayed. You can also decide to print one item from the sequence by providing its index.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print('Skillset: {0[1]}'.format(langs))\n\n#Skillset: C++<\/pre>\n\n\n\n<p>You can even send the list item as the positional parameters. To achieve this, unpack them using the * operator.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print('Skillset: {}'.format(*langs))\n\n#Skillset: C<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-formatting-dict-in-python\">Formatting Dict in Python<\/h4>\n\n\n\n<p>Format function allows using&nbsp;a dictionary as a parameter. See the below example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\" Jake's salary is {0[jake]} \\n Anand's salary is {0[anand]}\".format({'jake': '$100K', 'anand': '$120K'}))\n\n#Jake's salary is $100K \n#Anand's salary is $120K<\/pre>\n\n\n\n<p>You can format dictionary data using the keyworded arguments.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">print(\" Jake's salary is {sal[jake]} \\n Anand's salary is {sal[anand]}\".format(sal={'jake': '$100K', 'anand': '$120K'}))\n\n#Jake's salary is $100K \n#Anand's salary is $120K<\/pre>\n\n\n\n<p>There can be more complex usages of the Python format function which you can face in your work environments. Please do let us know if you like to add one of them here.<\/p>\n\n\n\n<p>To Learn Python from Scratch, Read the <a href=\"\/python-tutorial-step-by-step\/\" target=\"_blank\" rel=\"noopener noreferrer\">Python tutorial<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>String formatting is a basic concept in Python that allows you to modify and display text with ease. For this purpose, Python provides a string format() method which is a versatile and powerful tool for string formatting. In this tutorial, we will delve into this method, and its features, and learn how to use it [&hellip;]<\/p>\n","protected":false},"author":321,"featured_media":6902,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_post_was_ever_published":false},"categories":[92],"tags":[],"class_list":{"0":"post-6901","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python-programming-tutorials"},"jetpack_featured_media_url":"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/11\/Python-Format-How-To-Format-Data-Types-In-Python.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6901","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/users\/321"}],"replies":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/comments?post=6901"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6901\/revisions"}],"predecessor-version":[{"id":23564,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6901\/revisions\/23564"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/6902"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=6901"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=6901"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=6901"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}