{"id":741,"date":"2022-02-06T14:48:00","date_gmt":"2022-02-06T09:18:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=741"},"modified":"2023-08-15T17:18:46","modified_gmt":"2023-08-15T11:48:46","slug":"4-ways-of-string-formatting-in-python-guide","status":"publish","type":"post","link":"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide","title":{"rendered":"4 Ways of String Formatting in Python &#8211; Guide"},"content":{"rendered":"\n<p>This article will go over the four different types of string formatting techniques in Python.<\/p>\n\n\n\n<p>We&#8217;ll go over all four types of methods and their applications so we can understand the fundamentals of various string formatting techniques.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-introduction\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-introduction\"><\/a>Introduction<\/h1>\n\n\n\n<p>What is string formatting? Well, we can call it&nbsp;<strong>the process in which we inject things dynamically into the string and return the formatted version of that string<\/strong>.<\/p>\n\n\n\n<p><strong>There are 4 ways to perform string formatting<\/strong>&nbsp;that are all different from each other:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using % Operator (&#8220;old style&#8221;)<\/strong><\/li>\n\n\n\n<li><strong>Using format() string method<\/strong><\/li>\n\n\n\n<li><strong>Using String literals (f-string)<\/strong><\/li>\n\n\n\n<li><strong>Using String Template class<\/strong><\/li>\n<\/ul>\n\n\n\n<p>We will see the fundamentals of the ways mentioned above.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-1-using-modulo-operator\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-1-using-modulo-operator\"><\/a>1. Using % (modulo) Operator<\/h1>\n\n\n\n<p>This way of formatting the strings, use the&nbsp;<strong>% (modulo) operator<\/strong>. If you&#8217;re familiar with Python&#8217;s arithmetic operators, you&#8217;ll recognize that we use this operator to calculate the remainder of the dividend.<\/p>\n\n\n\n<p>The same operator we use in the oldest style of string formatting. Modulo (<code>%<\/code>) operators are also referred to as&nbsp;<strong>&#8220;String-formatting&#8221;<\/strong>&nbsp;or&nbsp;<strong>&#8220;String-interpolation&#8221;<\/strong>&nbsp;operators.<\/p>\n\n\n\n<p><strong>Here&#8217;s an example:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Use of the modulo operator for string formatting\nname = \"Python\"\nprint(\"Hello, %s\" % name)\n\n# ----------------OR--------------\n\nprint(\"Hello, %s!\" % 'Geeks')<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hello, Python\nHello, Geeks!<\/pre><\/div>\n\n\n\n<p>We use format specifiers to tell Python that the given value must be substituted in that specific position.<\/p>\n\n\n\n<p>We used the&nbsp;<code>\"%s\"<\/code>&nbsp;format specifier to insert the string&nbsp;<code>\"Python\"<\/code>&nbsp;in that specific position.<\/p>\n\n\n\n<p>We have some format specifiers that we use commonly:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>%s<\/strong>&nbsp;&#8211; for string<\/li>\n\n\n\n<li><strong>%d<\/strong>&nbsp;&#8211; for integers<\/li>\n\n\n\n<li><strong>%f<\/strong>&nbsp;&#8211; for floating-point values<\/li>\n\n\n\n<li><strong>%b<\/strong>&nbsp;&#8211; for binary format<\/li>\n\n\n\n<li><strong>%e<\/strong>&nbsp;&#8211; for floating-point exponent<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s look at the examples showing different formatting conditions.<\/p>\n\n\n\n<p><strong>Example 1: Formatting the integer values<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"I bought %d apples and %d oranges.\" %(6, 4))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">I bought 6 apples and 4 oranges.<\/pre><\/div>\n\n\n\n<p>We can insert multiple strings as well as we can use variables to insert objects in the string.<\/p>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">x = \"car\"\nprint(\"The dog %s down the %s.\" %('chased', x))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The dog chased down the car.<\/pre><\/div>\n\n\n\n<p>Using multiple format conversion types in a single string.<\/p>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">name = \"Yashwant\"\nprint(\"My %s %s bought the car worth $%d.\" %('friend', name, 15000))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">My friend Yashwant bought the car worth $15000.<\/pre><\/div>\n\n\n\n<p><strong>Floating-point Precision using the % operator<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"The length of land is: %2.3f metres\" %(85.52590))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The length of land is: 85.526 metres<\/pre><\/div>\n\n\n\n<p>Now you might wonder, why we used&nbsp;<code>%2.3f<\/code>.<\/p>\n\n\n\n<p><strong>Floating-point numbers<\/strong>&nbsp;use an&nbsp;<code>x.yf<\/code>&nbsp;format, where&nbsp;<code>x<\/code>&nbsp;is a minimum number of digits in a string and&nbsp;<code>yf<\/code>&nbsp;represents how many digits have to display after the decimal point.<\/p>\n\n\n\n<p><strong>If the whole number doesn&#8217;t have the specified number of digits then it might be padded with whitespace.<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"The length of land is: %7.3f metres\" %(85.52590))\nprint(\"The length of land is: %0.3f metres\" %(85.52590))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The length of land is:  85.526 metres\nThe length of land is: 85.526 metres<\/pre><\/div>\n\n\n\n<p>The first print statement is padded with whitespace in this case. There is a distinction between the two outcomes.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>To know more, click&nbsp;<a target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#printf-style-string-formatting\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-2-using-format-method\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-2-using-format-method\"><\/a>2. Using format() method<\/h1>\n\n\n\n<p>This method is introduced to get rid of the&nbsp;<strong>% operator formatting<\/strong>. This method is suitable for handling complex string formatting more efficiently.<\/p>\n\n\n\n<p><code>str.format()<\/code>&nbsp;method is pretty simple and fast as compared to&nbsp;<code>\"%\"<\/code>&nbsp;operator formatting and is introduced in Python3.<\/p>\n\n\n\n<p>In this technique of formatting, formatters work by putting the placeholders enclosed by pair of curly braces&nbsp;<code>\"{ }\"<\/code>&nbsp;and calling the&nbsp;<code>str.format()<\/code>&nbsp;method.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>&#8220;String goes { } and here { }&#8221;.format(&#8220;here&#8221; , &#8220;also&#8221;)<\/strong><\/p>\n<\/blockquote>\n\n\n\n<p><strong>Here&#8217;s an example:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Formatting using format() method\nprint(\"Hey {}, Welcome {}.\".format('Geeks', 'to GeekPython'))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hey Geeks, Welcome to GeekPython.<\/pre><\/div>\n\n\n\n<p>Let&#8217;s see some examples<\/p>\n\n\n\n<p>We can use index-based positioning to insert the object into the string<\/p>\n\n\n\n<p><strong>Example &#8211; 1: Using index-based positioning<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"{1}, there is a {2} {0} ahead.\".format(\"error\", \"Caution\", \"Python\"))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Caution, there is a Python error ahead.<\/pre><\/div>\n\n\n\n<p><strong>Example &#8211; 2:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"Python: {x}, Inventor: {y}, Version: {z}\".format(x=1991,\n                                                        y=\"Guido\",\n                                                        z=3.11))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Python: 1991, Inventor: Guido, Version: 3.11<\/pre><\/div>\n\n\n\n<p><strong>Example &#8211; 3: Reusing the same value<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"The first {obj} was easy, the second {obj} was intermediate \"\n      \"but the third {obj} was very tough.\".format(obj=\"hurdle\"))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The first hurdle was easy, the second hurdle was intermediate but the third hurdle was very tough.<\/pre><\/div>\n\n\n\n<p><strong>Floating-point Precision with<\/strong>&nbsp;<code>.format()<\/code>&nbsp;method<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(\"The decimal number is: {0:1.3f}\".format(54.123456, 23.5466))\nprint(\"The decimal number is: {1:1.3f}\".format(54.123456, 23.5466))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The decimal number is: 54.123\nThe decimal number is: 23.547<\/pre><\/div>\n\n\n\n<p>We have seen&nbsp;<strong>floating-point precision<\/strong>&nbsp;using the&nbsp;<code>%<\/code>&nbsp;operator where the format was&nbsp;<code>x.yf<\/code>&nbsp;but here the case is a bit different.<\/p>\n\n\n\n<p>Here, the&nbsp;<strong>Syntax<\/strong>&nbsp;is<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>{ [ index ] : [ width ] . [ precision ] [ type ] }<\/strong><\/p>\n<\/blockquote>\n\n\n\n<p>If we breakdown&nbsp;<code>{0:1.3f}<\/code>&nbsp;this then:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>0<\/code>&nbsp;&#8211; is the index value<\/li>\n\n\n\n<li><code>1<\/code>&nbsp;&#8211; is the width<\/li>\n\n\n\n<li><code>3<\/code>&nbsp;&#8211; is the precision or no. of digits to be displayed after the decimal point<\/li>\n\n\n\n<li><code>f<\/code>&nbsp;&#8211; is the type of format code<\/li>\n<\/ul>\n\n\n\n<p>Here are the common types that we can use with format code:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>&#8220;d&#8221;<\/strong>&nbsp;&#8211; for integers<\/li>\n\n\n\n<li><strong>&#8220;f&#8221;<\/strong>&nbsp;&#8211; for floating-point numbers<\/li>\n\n\n\n<li><strong>&#8220;s&#8221;<\/strong>&nbsp;&#8211; for string<\/li>\n\n\n\n<li><strong>&#8220;e&#8221;<\/strong>&nbsp;&#8211; for floating-point in an exponent format<\/li>\n\n\n\n<li><strong>&#8220;o&#8221;<\/strong>&nbsp;&#8211; for octal numbers<\/li>\n\n\n\n<li><strong>&#8220;x&#8221;<\/strong>&nbsp;&#8211; for hexadecimal numbers<\/li>\n\n\n\n<li><strong>&#8220;b&#8221;<\/strong>&nbsp;&#8211; for binary numbers<\/li>\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>To know more, click&nbsp;<a target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/string.html#formatstrings\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-3-using-f-string-literal-string-interpolation\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-3-using-f-string-literal-string-interpolation\"><\/a>3. Using f-string (Literal String Interpolation)<\/h1>\n\n\n\n<p>Literal string interpolation, a new mechanism to format strings which were introduced in&nbsp;<a target=\"_blank\" href=\"https:\/\/www.python.org\/dev\/peps\/pep-0498\/\" rel=\"noreferrer noopener\">PEP 498<\/a>.<\/p>\n\n\n\n<p>These strings are called&nbsp;<a target=\"_blank\" href=\"https:\/\/geekpython.in\/f-string-in-python\" rel=\"noreferrer noopener\"><strong>f-strings<\/strong><\/a>&nbsp;because of their leading character&nbsp;<code>\"f\"<\/code>&nbsp;that is used to denote the string and here, f &#8211; stands for&nbsp;<strong>&#8220;formatted&#8221; string.<\/strong><\/p>\n\n\n\n<p>f-strings are string literals that are prefixed by the letter&nbsp;<code>\"f\"<\/code>.<\/p>\n\n\n\n<p>f-string uses the same format specifier mini-language that is used for&nbsp;<code>str.format()<\/code>.<\/p>\n\n\n\n<p><strong>Here&#8217;s an example:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">name = \"Sachin\"\nprint(f\"Hi, I am {name}.\")<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hi, I am Sachin.<\/pre><\/div>\n\n\n\n<p>Let&#8217;s see the use case of the f-strings in different conditions:<\/p>\n\n\n\n<p><strong>Example &#8211; 1: Using multiple expressions<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">name = \"Sachin\"\nx = 45\ny = 12\n\nprint(f\"Hi, I am {name} and I run {8*(x + y)} metres daily.\")<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hi, I am Sachin and I run 456 metres daily.<\/pre><\/div>\n\n\n\n<p><strong>Example &#8211; 2: Using an f-string inside the<\/strong>&nbsp;<code>function<\/code><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">def write(name, say):\n    return f\"My name is {name} and I am saying {say}.\"\n\noutput = write(\"Sachin\", \"Good luck\")\nprint(output)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">My name is Sachin and I am saying Good luck.<\/pre><\/div>\n\n\n\n<p><strong>Example &#8211; 3: Using<\/strong>&nbsp;<code>lambda<\/code>&nbsp;expression inside f-string<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">print(f\"Using lambda function: {(lambda x: x*13)(3)}\")<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Using lambda function: 39<\/pre><\/div>\n\n\n\n<p><strong>Floating-point Precision in f-string<\/strong><\/p>\n\n\n\n<p><strong>Syntax<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>{ value : { width } . { precision } }<\/strong><\/p>\n<\/blockquote>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">width = 5\nprecision = 7\nvalue = 15.155245\n\nprint(f\"The result is: {value:{width}.{precision}}\")<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The result is: 15.15525<\/pre><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>To know more, click&nbsp;<a target=\"_blank\" href=\"https:\/\/geekpython.in\/f-string-in-python\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-4-string-template-class\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-4-string-template-class\"><\/a>4. String Template Class<\/h1>\n\n\n\n<p>In this method, we use&nbsp;<code>\"$\"<\/code>&nbsp;before the placeholders which are enclosed with&nbsp;<code>{ }<\/code>&nbsp;curly braces.<\/p>\n\n\n\n<p>In this style of formatting, we use the&nbsp;<code>Template<\/code>&nbsp;class to make a template and once the template has been created then we can perform substitution by calling two methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>substitute()<\/code>: This method returns a new string which results when the values of mapping are substituted for the placeholders in the Template. If there are placeholders that are not present in the mapping, a&nbsp;<code>KeyError<\/code>&nbsp;will be raised.<\/li>\n\n\n\n<li><code>safe_substitute()<\/code>: This is similar to the&nbsp;<code>substitute()<\/code>&nbsp;method, except that KeyErrors are never raised (due to placeholders missing from the mapping). When a placeholder is missing, the original placeholder will appear in the resulting string.&nbsp;<a target=\"_blank\" href=\"https:\/\/www.python.org\/dev\/peps\/pep-0292\/\" rel=\"noreferrer noopener\">(Source)<\/a><\/li>\n<\/ul>\n\n\n\n<p><strong>Take a look at the example for a better understanding:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from string import Template\n\nname = \"Sachin\"\ngreet = \"Welcome\"\n\nmy_str = Template(\"Hello $x, $y here.\")\nprint(my_str.substitute(x=name, y=greet))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hello Sachin, Welcome here.<\/pre><\/div>\n\n\n\n<p>Here&nbsp;<code>\"x\"<\/code>&nbsp;and&nbsp;<code>\"y\"<\/code>&nbsp;are the placeholders prefixed by&nbsp;<code>\"$\"<\/code>&nbsp;substituted by the values of the mapping&nbsp;<code>\"name\"<\/code>&nbsp;and&nbsp;<code>\"greet\"<\/code>.<\/p>\n\n\n\n<p><strong>Example &#8211; 1: Raising<\/strong>&nbsp;<code>KeyError<\/code><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from string import Template\n\nname = \"Sachin\"\ngreet = \"Welcome\"\n\nmy_str = Template(\"Hello $x, $y here.\")\nprint(my_str.substitute(x=name))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Traceback (most recent call last):\n  ....\nKeyError: 'y'<\/pre><\/div>\n\n\n\n<p>The above code snippet raised a&nbsp;<code>KeyError<\/code>&nbsp;because we didn&#8217;t specify the mapping for the placeholder&nbsp;<code>\"$y\"<\/code>. But if we use&nbsp;<code>\"safe_substitute()\"<\/code>&nbsp;method then it will not raise&nbsp;<strong>KeyError<\/strong>.<\/p>\n\n\n\n<p><strong>Example &#8211; 2: Using<\/strong>&nbsp;<code>safe_substitute<\/code>&nbsp;method<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from string import Template\n\ncharacter = \"Iron man\"\nname = \"Stan Lee\"\ncountry = \"USA\"\n\nmy_str = Template(\"$x was created by $y for Marvel in $country\")\nprint(my_str.safe_substitute(x=character, y=name))<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Iron man was created by Stan Lee for Marvel in $country<\/pre><\/div>\n\n\n\n<p>We didn&#8217;t specify the mapping for&nbsp;<code>\"$country\"<\/code>&nbsp;here, but there was no error because we used the&nbsp;<code>safe_substitute<\/code>&nbsp;method.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>To know more, click&nbsp;<a target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/string.html#template-strings\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-comparing\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-comparing\"><\/a>Comparing<\/h1>\n\n\n\n<p>Consider the following example in which we are comparing the execution time of the code snippets of different formatting methods.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import timeit\n\n# Using % operator\nmod = timeit.timeit(\"\"\"\nchar = 'Iron man' \nname = 'Stan Lee' \n'%s was created by %s' %(char, name)\n\"\"\", number=1000000)\nprint(mod)\n\n# Using format() method\nformat_method = timeit.timeit(\"\"\"\nchar = 'Iron man' \nname = 'Stan Lee'\n'{} was created by {}.'.format(char, name)\n\"\"\", number=1000000)\nprint(format_method)\n\n# Using f-string\nfst = timeit.timeit(\"\"\"\nchar = 'Iron man' \nname = 'Stan Lee'\nf'{char} was created by {name}.'\n\"\"\", number=1000000)\nprint(fst)\n\n# Using Template Class\ntcl = timeit.timeit(\"\"\"\nfrom string import Template\nchar = 'Iron man'\nname = 'Stan Lee'\nmy_str = Template(\"$x was created by $y.\")\nmy_str.substitute(x=char, y=name)\"\"\", number=1000000)\nprint(tcl)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">0.351656400016509\n0.4346434000181034\n0.1398726999759674\n3.969239500002004<\/pre><\/div>\n\n\n\n<p>We obtained the time required by each code snippet to complete one million executions, and thus we can conclude that the f-string was relatively fast, taking nearly 0.14 seconds, which is significantly less than other methods.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide#heading-conclusion\"><\/a>Conclusion<\/h2>\n\n\n\n<p>We can conclude that all of the methods used for string formatting are distinct from one another, with each having its own formatting style.<\/p>\n\n\n\n<p>To compensate for the lack of efficiency or ability to handle complex formatting, new methods were developed over time.<\/p>\n\n\n\n<p>We can choose the best and most efficient string formatting technique for us now that we have seen and compared all of the different types of string formatting.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might like if you like this article<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/convert-bytes-into-string\" rel=\"noreferrer noopener\">How to convert bytes into a string in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/display-images-in-jupyter-notebook\" rel=\"noreferrer noopener\">Different ways to display images in Jupyter Notebook<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/context-managers-and-python-with-statement\" rel=\"noreferrer noopener\">What are context manager and the with statement in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/insert-vs-append-vs-extend\" rel=\"noreferrer noopener\">Difference between the list insert(), append() and extend() methods<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/access-list-values-within-the-dictionary\" rel=\"noreferrer noopener\">How to access list values within a dictionary in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-sort-vs-sorted\" rel=\"noreferrer noopener\">What is the difference between sort and sorted in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/init-vs-new\" rel=\"noreferrer noopener\">The concept of constructor and initializer in Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article will go over the four different types of string formatting techniques in Python. We&#8217;ll go over all four types of methods and their applications so we can understand the fundamentals of various string formatting techniques. Introduction What is string formatting? Well, we can call it&nbsp;the process in which we inject things dynamically into [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":743,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12],"class_list":["post-741","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/741","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=741"}],"version-history":[{"count":2,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/741\/revisions"}],"predecessor-version":[{"id":1384,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/741\/revisions\/1384"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/743"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=741"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=741"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=741"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}