{"id":12072,"date":"2023-08-27T23:31:29","date_gmt":"2023-08-27T18:01:29","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=12072"},"modified":"2023-08-27T23:31:54","modified_gmt":"2023-08-27T18:01:54","slug":"python-string-interpolation","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/python-string-interpolation\/","title":{"rendered":"Python String Interpolation: 4 Methods with Examples"},"content":{"rendered":"\n<p>String interpolation is a technique to add values of variables into placeholders in a particular string. The changes carried out by these methods are dynamically implemented and make it easy for the developers to design a program.&nbsp;<\/p>\n\n\n\n<p>The literal meaning of the word interpolation is to put in between or among others. In this article, we will understand four string interpolation methods in Python with syntax and supporting examples so that you can choose the one that suits you best.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Methods of String Interpolation in Python<\/h2>\n\n\n\n<p>Python supports multiple ways to format strings but we will be only focusing on those that are efficient and mainly used by programmers.<\/p>\n\n\n\n<p><strong>String Interpolation in Python can be done using the following ways:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>%- formatting<\/li>\n\n\n\n<li>str.format()<\/li>\n\n\n\n<li>f-string<\/li>\n\n\n\n<li>String Template Class<\/li>\n<\/ul>\n\n\n\n<p><strong>Also Read: <a href=\"https:\/\/codeforgeek.com\/python-check-if-string-contains-substring\/\" data-type=\"URL\" data-id=\"https:\/\/codeforgeek.com\/python-check-if-string-contains-substring\/\" target=\"_blank\" rel=\"noreferrer noopener\">Check if a Python String Contains a Substring<\/a><\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">%- formatting<\/h3>\n\n\n\n<p>This is the most basic and straightforward way of formatting a string. The modulo (%) operator can insert multiple variables in a string.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>%s &#8211; string insertion<\/li>\n\n\n\n<li>%c &#8211; character insertion<\/li>\n\n\n\n<li>%d &#8211; integer value insertion<\/li>\n\n\n\n<li>%f &#8211; floating point values insertion<\/li>\n\n\n\n<li>Refer to more<a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#printf-style-string-formatting\" target=\"_blank\" rel=\"noopener\"> <strong><em>here<\/em><\/strong><\/a><\/li>\n<\/ul>\n\n\n\n<p>The above-mentioned are some format specifiers, that replace themselves with value mentions at the end of the string. Refer to the following example.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nname = &quot;Tanvi&quot;\nprint(&quot;%s is learning Python&quot; %name)\nprint(&quot;%s refers %s website&quot;%(name,&#039;AskPython&#039;))\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nTanvi is learning Python\nTanvi refers AskPython website\n<\/pre><\/div>\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nx = 24\nprint(&quot;We have %d hours a day.&quot;%x)\n\ny = 8.5\nprint(&quot;We spend around %f hours sleeping.&quot;%y)\n\nz = &quot;a&quot;\nprint(&quot;The first alphabet is %c.&quot;%z)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nWe have 24 hours a day.\nWe spend around 8.500000 hours sleeping.\nThe first alphabet is a.\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">str.format()<\/h3>\n\n\n\n<p>It is a built-in function that makes formatting a string in Python even more convenient. The position of variables to be added is taken by curly braces &#8211; {}, and the value of the variable is passed after the string ends by calling the str.format() function. This way of Python string formatting is considered more efficient is it can handle variables of all kinds in one uniform way.<\/p>\n\n\n\n<p><strong>Syntax:\u00a0<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n{}.format(value\/s) \n<\/pre><\/div>\n\n\n<p><strong>Parameters:&nbsp;<\/strong><\/p>\n\n\n\n<p>The parameter passed can be multiple too. The <strong>value <\/strong>can be an integer, floating point value, character, string, or any other variable.<\/p>\n\n\n\n<p><strong>Example 1: Single Variable<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#Method 1:\nstring1 = &quot;AskyPython helps you to learn {}&quot;\nprint(string1.format(&quot;Python&quot;))\n\n#Method 2:\nprint(&quot;{} is interpreted language&quot;.format(&quot;Python&quot;))\nprint(&quot;Python was invented in {}&quot;.format(1991))\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nAskyPython helps you to learn Python\nPython is interpreted language\nPython was invented in 1991\n<\/pre><\/div>\n\n\n<p><strong>Example 2: Multiple Variable<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nprint(&quot;Every month, over {} new computer {} are released.&quot;.format(5000, &quot;Viruses&quot;))\nx1 = 1979\nprint(&quot;The {} hard drive was made in {}.&quot;.format(&quot;first&quot;,x1))\nprint(&quot;\\n&quot;)\n#will return error\nprint(&quot;{} is {}, {} {} programing language&quot;.format(&quot;Python&quot;,&quot;high-level&quot;, &quot;interpreted&quot;))\n<\/pre><\/div>\n\n\n<p><strong>NOTE: <\/strong>The number of placeholders ( {} ) should be equal to the number of variable values passed in .format(). Or else, the tuple index will be out of range and thus IndexError will occur.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nEvery month, over 5000 new computer Viruses are released.\nThe first hard drive was made in 1979.\n\nTraceback (most recent call last):\nFile &quot;&quot;, line 8, in\nIndexError: Replacement index 3 out of range for positional args tuple\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">f-string<\/h3>\n\n\n\n<p>Also known as formatted string literals. This is a way of literal string interpolation that is more readable, convenient, and efficient but it is available in Python3.6 and later versions only. F-strings are faster than both the %-formatting method and str.format() method. The string is initialized with &#8220;f&#8221; as a prefix and mentions the variable names in {} at their correct position.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nx1 = &quot;Python&quot;\nprint(f&quot;Ask{x1} has articles on the {x1} language&quot;)\n\nx2 = 1991\nprint(f&quot;{x1} was invented in {x2}&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nAskPython has articles on the Python language\nPython was invented in 1991\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">String Template Class<\/h3>\n\n\n\n<p>This method is a bit lengthy and provides less convenience when compared with other methods of string formatting in Python. Firstly, the Template class is needed to import from the string module in Python. Template strings support $-based substitutions. $identifier names a substitution placeholder matching a mapping key of &#8220;identifier&#8221;. By default, &#8220;identifier&#8221; is restricted to any case-insensitive ASCII alphanumeric string (including underscores).<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nname = &quot;Tanvi&quot;\nstr1 = Template(&quot;My name is $name&quot;)\nprint(str1.substitute(name = name))\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nMy name is Tanvi\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Frequently Asked Questions (FAQs)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is Python string interpolation?<\/h3>\n\n\n\n<p>Python string interpolation is a method of substitution placeholders in a string with values. Placeholders are basically variables to which we can assign values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What are the four interpolation methods?<\/h3>\n\n\n\n<p>The four methods of string interpolation are <strong>%- formatting<\/strong>, <strong>str.format()<\/strong>, <strong>f-string<\/strong> and <strong>String Template Class<\/strong> where the most recommended method is f-string introduced in Python 3.6.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Which method is best for interpolation?<\/h3>\n\n\n\n<p>The best method for string interpolation is to use <strong>f-string<\/strong> which is a relatively new string formatting mechanism that lets us embed the value of Python expressions inside string literals which also helps in increasing overall readability.\u00a0\u00a0<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u00a0What are the benefits of string interpolation?<\/h3>\n\n\n\n<p>There are many benefits of using string interpolation such as a <strong>better interface<\/strong>,<strong> creating templates<\/strong>, <strong>displaying data<\/strong>, etc. But one of the key benefits is to <strong>create dynamic content<\/strong>, you can insert different data to generate customised results.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is %s and %d in Python?<\/h3>\n\n\n\n<p>In Python, both <strong>%s<\/strong> and <strong>%d<\/strong> are placeholders where <strong>%s\u00a0 is used for inserting string values<\/strong> into a string and <strong>%d is used for inserting integer values<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is string interpolation data binding?<\/h3>\n\n\n\n<p>Data binding means combining source data with target data. String interpolation is a certain case of data binding, where the source data is a variable and the target data is a string.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between string interpolation and concatenation?<\/h3>\n\n\n\n<p>String concatenations means combining two or more strings together, one after the other. Whereas string interpolation is a process of inserting values, variables, or expressions into a string.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we understood multiple ways to perform string interpolation in Python. The most commonly recommended methods are either<strong> f-string<\/strong> or<strong> str.format()<\/strong>, as they have fewer chances to return any kind of errors.<\/p>\n\n\n\n<p><strong>Read More: <a href=\"https:\/\/codeforgeek.com\/python-keywords\/\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/codeforgeek.com\/python-keywords\/\" rel=\"noreferrer noopener\">Python Keywords \u2013 Simply Explained!<\/a><\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">References<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/peps.python.org\/pep-0498\/#id13\" target=\"_blank\" rel=\"noopener\">https:\/\/peps.python.org\/pep-0498\/#id13<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/docs.python.org\/3\/library\/string.html#formatstrings\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.python.org\/3\/library\/string.html#formatstrings<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/docs.python.org\/3\/library\/string.html#template-strings\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.python.org\/3\/library\/string.html#template-strings<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>String interpolation is a technique to add values of variables into placeholders in a particular string. The changes carried out by these methods are dynamically implemented and make it easy for the developers to design a program.&nbsp; The literal meaning of the word interpolation is to put in between or among others. In this article, [&hellip;]<\/p>\n","protected":false},"author":73,"featured_media":21687,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[134],"tags":[],"class_list":["post-12072","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation.png",1000,600,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation-300x180.png",300,180,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation-768x461.png",768,461,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation.png",1000,600,false],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation.png",1000,600,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/07\/Python-String-Interpolation.png",1000,600,false]},"uagb_author_info":{"display_name":"Ninad Pathak","author_link":"https:\/\/codeforgeek.com\/author\/ninad\/"},"uagb_comment_info":0,"uagb_excerpt":"String interpolation is a technique to add values of variables into placeholders in a particular string. The changes carried out by these methods are dynamically implemented and make it easy for the developers to design a program.&nbsp; The literal meaning of the word interpolation is to put in between or among others. In this article,&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/12072","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/73"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=12072"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/12072\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/21687"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=12072"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=12072"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=12072"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}