{"id":1887,"date":"2019-12-29T12:03:44","date_gmt":"2019-12-29T12:03:44","guid":{"rendered":"https:\/\/www.askpython.com\/?p=1887"},"modified":"2022-08-06T13:09:15","modified_gmt":"2022-08-06T13:09:15","slug":"python-template-strings","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/string\/python-template-strings","title":{"rendered":"Python Template Strings"},"content":{"rendered":"\n<p>Python&#8217;s <strong>Template String<\/strong> <strong>Class<\/strong> provides a way for simple string substitution, wherein the template fields are substituted with suitable replacement strings provided by the user.<\/p>\n\n\n\n<p>Sometimes, it may be a preference to have an easier to replace string, rather than using other format strings for substitution. Template Strings are used exactly for this purpose, to easily replace strings with minimum hassles and without exceptions.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">String Template Rules<\/h2>\n\n\n\n<p>Template Strings support <code><strong>$<\/strong><\/code> based substitutions, which conform to the following rules :<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code><strong>$$<\/strong><\/code> -&gt; This is an Escape sequence for the single <code>$<\/code> symbol, since it would be classified as a modifier otherwise.<\/li><li><code>$<strong>identifier<\/strong><\/code> -&gt; This is a Substitution placeholder.<\/li><li><code>$<strong>{identifier}<\/strong><\/code> -&gt; Equivalent to <code>$<strong>identifier<\/strong><\/code>. Is used when valid characters appear after the placeholder but are not a part of the placeholder.<\/li><li>Any other appearance of <code>$<\/code> will raise a <code><strong>ValueError<\/strong><\/code> Exception.<\/li><\/ul>\n\n\n\n<p>Here is an example to demonstrate basic Template Substitution:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom string import Template\n\n# Create a template with &#039;name&#039; as the placeholder\ntemplate = Template(&#039;Hello $name!&#039;)\n\nstudent = &#039;Amit&#039;\n\n# Perform the template substitution and print the result\nprint(template.substitute(name=student))\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nHello Amit!\n<\/pre><\/div>\n\n\n<p>Here is another snippet to demonstrate the other rules of Template Substitution:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom string import Template\n\n# Create a template with $CODE as the placeholder\n# The $$ is to escape the dollar sign\ntemplate = Template(&#039;The generated Code is ${CODE}-$$100&#039;)\n\ncode = &#039;H875&#039;\n\n# Perform the template substitution and print the result\nprint(template.substitute(CODE=code))\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nThe generated Code is H875-$100\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">String Template Class methods<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. The Template Constructor<\/h3>\n\n\n\n<p>We have already encountered this in our earlier snipper, where we create our string template object using <code>Template(template_string)<\/code>.<\/p>\n\n\n\n<p>Format: <code>template_object = Template(template_string)<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. substitute(mapping, **kwargs)<\/h3>\n\n\n\n<p>This is also a part of our earlier snippet, which performs a template substitution from <code><em>mapping<\/em><\/code> to the keyword arguments <code><em>kwargs<\/em><\/code>.<\/p>\n\n\n\n<p>The second argument is a <code>**kwargs<\/code> because we pass keyword arguments as placeholders for substitution. Therefore, it is passed as a Dictionary for template substitution.<\/p>\n\n\n\n<p>To illustrate this point, we show how to pass a dictionary into the template string.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom string import Template\n\ntemplate = Template(&#039;The shares of $company have $state. This is $reaction.&#039;)\n\n# Perform the template substitution and print the result\nprint(template.substitute(state = &#039;dropped&#039;, company=&#039;Google&#039;, reaction=&#039;bad&#039;))\n\n# Perform substitution by passing a Dictionary\ndct = {&#039;state&#039;: &#039;risen&#039;, &#039;company&#039;: &#039;Apple&#039;, &#039;reaction&#039;: &#039;good&#039;}\n\nprint(template.substitute(**dct))\n\n# Incomplete substitution results in a KeyError\ntry:\n    template.substitute(state = &#039;dropped&#039;)\nexcept KeyError:\n    print(&#039;Incomplete substitution resulted in KeyError!&#039;)\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nThe shares of Google have dropped. This is bad.\nThe shares of Apple have risen. This is good.\nIncomplete substitution resulted in KeyError!\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3. safe_substitute(mapping, **kwargs)<\/h3>\n\n\n\n<p>This is similar to <code>substitute()<\/code>,  except that if placeholders are missing from <em>mapping<\/em> and <em>kwargs<\/em>, instead of raising a <a href=\"https:\/\/docs.python.org\/3\/library\/exceptions.html#KeyError\" target=\"_blank\" rel=\"noopener\"><code>KeyError<\/code><\/a> exception, the original placeholder will appear in the resulting string intact.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom string import Template\n\ntemplate = Template(&#039;The shares of $company have $state. This is $reaction.&#039;)\n\nprint(template.safe_substitute(company=&#039;Google&#039;))\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nThe shares of Google have $state. This is $reaction.\n<\/pre><\/div>\n\n\n<p>As you can see, there is no <code>KeyError<\/code>, resulting in an incomplete, but error-free substitution. This is why the substitution is &#8216;safe&#8217;.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Template Class attributes<\/h2>\n\n\n\n<p>The Template object has the <code>template<\/code> attribute, which returns the template string. Although it can be modified, it is good practice to not change this attribute value.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom string import Template\n\nt = Template(&#039;Hello $name, are you $cond?&#039;)\nprint(t.template)\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nHello $name, are you $cond?\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned about the String Template Class, and some of it&#8217;s methods for regular and safe substitution of template strings. We also saw how we could use them for simple and easy string substitution.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/docs.python.org\/3\/library\/string.html#template-strings\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">Python Template Strings<\/a><\/li><li>JournalDev article on Template Strings<\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s Template String Class provides a way for simple string substitution, wherein the template fields are substituted with suitable replacement strings provided by the user. Sometimes, it may be a preference to have an easier to replace string, rather than using other format strings for substitution. Template Strings are used exactly for this purpose, to [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-1887","post","type-post","status-publish","format-standard","hentry","category-string"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1887","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=1887"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1887\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=1887"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=1887"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=1887"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}