{"id":3810,"date":"2018-07-22T23:12:00","date_gmt":"2018-07-22T17:42:00","guid":{"rendered":"https:\/\/www.csestack.org\/?p=3810"},"modified":"2019-03-16T17:36:41","modified_gmt":"2019-03-16T12:06:41","slug":"python-string-formatting","status":"publish","type":"post","link":"https:\/\/www.csestack.org\/python-string-formatting\/","title":{"rendered":"4 Python String Formatting Every Python Developer should Master"},"content":{"rendered":"<p>Coming so far with programming, we know, the string is a set of characters. And no doubt, it is one of the most useful data types in any programming language.<\/p>\n<p><strong>What is Python String Formatting?<\/strong><\/p>\n<p>Instead of using a string as it is, many times we need to stuff the string with other data value. And it is called as string formatting.<\/p>\n<p>You will learn more about it as I explain string formatting with an example below.<\/p>\n<p>In this tutorial, you will also learn to use different approaches for string formatting in Python.<\/p>\n<div class=\"post_container_links\">\n<p><strong>Table of contents<\/strong><\/p>\n<ol>\n<li><a href=\"#percent-operator\">String Formatting using %\u00a0Operator<\/a><\/li>\n<li><a href=\"#str-format\">String Formatting using str.format()<\/a><\/li>\n<li><a href=\"#f-strings\">(Python 3.6+) String Formatting using f-Strings<\/a><\/li>\n<li><a href=\"#template\">Template Strings (Standard Library)<\/a><\/li>\n<\/ol>\n<\/div>\n<p>To make the best use of this tutorial and mastering string formatting, open your Python interpreter and try running commands as we go with this tutorial.<\/p>\n<p>So, without squandering any further time, let&#8217;s discuss now.<\/p>\n<h4 id=\"percent-operator\">1) String Formatting using %\u00a0Operator<\/h4>\n<p>This is the oldest string formatting method.<\/p>\n<pre>&gt;&gt;&gt; lang = 'Python'\r\n&gt;&gt;&gt;'You are working with %s' % lang\r\n\"You are working with Python\"<\/pre>\n<p>Here, we are substituting string value. %s is a format specifier for\u00a0string\u00a0data. Other than string, you can substitute any other data types as well.<\/p>\n<p>Below is an example where the hexadecimal value is substituted.<\/p>\n<pre>&gt;&gt;&gt; noErr = 45565\r\n&gt;&gt;&gt; '%x' % errno\r\n'b1fd'<\/pre>\n<p>%x is a format specifier for hexadecimal data. With this format specifier, you can convert an integer value into the hex decimal value and then formate it into the string.<\/p>\n<p>Always print hexadecimal values in the\u00a0standard format by appending &#8220;0x&#8221; before the hexadecimal string. It makes easy for the end user to identify the formatting of data value.<\/p>\n<p>If there are multiple substitutions or if you want to stuff multiple values into the single string, you need to pass those values as tuple elements.<\/p>\n<pre>&gt;&gt;&gt; lang = 'Python'\r\n&gt;&gt;&gt; noErr = 45565\r\n&gt;&gt;&gt; 'You are working with %s. Please refer 0x%x error.' % (lang, noErr)\r\n'You are working with Python. Please refer 0xb1fd error.'<\/pre>\n<p>You can also pass multiple substitute variables using dictionary name-value pair.<\/p>\n<pre>&gt;&gt;&gt; lang = 'Python'\r\n&gt;&gt;&gt; noErr = 45565\r\n&gt;&gt;&gt; 'You are working with %(lang)s. Please refer 0x%(noErr)x error.' % {\r\n... \"lang\": lang, \"noErr\": noErr}\r\n'You are working with Python. Please refer 0xb1fd error.'<\/pre>\n<p>Here you don&#8217;t need to worry about the sequence of substitute variables.<\/p>\n<h4 id=\"str-format\">2) String Formatting using str.format()<\/h4>\n<p>You can call the format method using the str string object.<\/p>\n<pre>&gt;&gt;&gt; lang = 'Python'\r\n&gt;&gt;&gt; ''You are working with\u00a0 {}'.format(lang)\r\n'You are working with Python'<\/pre>\n<p>With this approach, passing the name-value pairs as an argument to the format method is easy.<\/p>\n<pre>&gt;&gt;&gt; lang = 'Python'\r\n&gt;&gt;&gt; noErr = 45565\r\n&gt;&gt;&gt; 'You are working with {lang}. Please refer {noErr:x} error.'.format(\u00a0\r\n... lang=lang, noErr=noErr)\r\n'You are working with Python. Please refer 0xb1fd error.'<\/pre>\n<h4 id=\"f-strings\">3) String Formatting using f-Strings (Python 3.6+)<\/h4>\n<p>It is also called as String Interpolation.<\/p>\n<p><strong>Note:<\/strong> <a href=\"https:\/\/docs.python.org\/3\/reference\/lexical_analysis.html#f-strings\" target=\"_blank\" rel=\"noopener\">f-string formatting<\/a> approach is new. And it only works with the Python 3 having version 3.6 or higher.<\/p>\n<pre>&gt;&gt;&gt; lang = 'Python'\r\n&gt;&gt;&gt; f'You are working with {lang}.'\r\nYou are working with Python.<\/pre>\n<p><strong>How to Evaluate\u00a0Expression in Python String Formatting?<\/strong><\/p>\n<p>You can also evaluate mathematical operations inside the f-string. It is more like embedding Python expressions inside the string to evaluate and print the result.<\/p>\n<pre>&gt;&gt;&gt; p = 11\r\n&gt;&gt;&gt; q = 9\r\n&gt;&gt;&gt; f'Addition of two number is {p + q} and multiplication is {p * q}.'\r\nAddition of two number is 20 and multiplication is 99.'<\/pre>\n<p>If you need to evaluate <a href=\"https:\/\/www.csestack.org\/python-numeric-data-types-examples\/\">numerical\u00a0data types<\/a>\u00a0expression and substitute result\u00a0into the string, use this method.<\/p>\n<h4 id=\"template\">4) Template Strings (Standard Library)<\/h4>\n<p>So another approach you can use and it is\u00a0called as\u00a0a template string. You need to import the Template module from a string.<\/p>\n<p>First, make the template object using Template(). You can format the substitution variable names by prefixing $ sign. And then substitute the value for the variable.<\/p>\n<pre>&gt;&gt;&gt; name = Alice\r\n&gt;&gt;&gt; from string import Template\r\n&gt;&gt;&gt; t = Template('My name is $name.')\r\n&gt;&gt;&gt; t.substitute(name=name)\r\n'My name is Alice.'<\/pre>\n<p>That&#8217;s it all from\u00a0Python string formatting tutorial. If you give an attention and try to run commands for each formatting approach, this topic is not much difficult.<\/p>\n<p><strong>Other Python String Tutorials:<\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/www.csestack.org\/reverse-string-in-python-using-extended-slice-syntax\/\" target=\"_blank\" rel=\"noopener noreferrer\">Reverse String in Python using Extended Slice Syntax<\/a><\/li>\n<li><a href=\"http:\/\/www.csestack.org\/get-permutations-of-string-in-python-itertools\/\" target=\"_blank\" rel=\"noopener noreferrer\">Get all the Permutations of String<\/a><\/li>\n<\/ul>\n<p>You can keep this string formatting list handy and use it as per your requirement.<\/p>\n<p>Let me know your opinion using different string formatting. Which formatting do you prefer? Write your experience in the comment.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,73],"tags":[72,257],"class_list":["post-3810","post","type-post","status-publish","format-standard","hentry","category-code","category-python","tag-python","tag-python-string"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>4 Python String Formatting Every Python Developer should Master<\/title>\n<meta name=\"description\" content=\"What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.csestack.org\/python-string-formatting\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"4 Python String Formatting Every Python Developer should Master\" \/>\n<meta property=\"og:description\" content=\"What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.csestack.org\/python-string-formatting\/\" \/>\n<meta property=\"og:site_name\" content=\"CSEstack\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/aniruddha.ca\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/aniruddha.ca\" \/>\n<meta property=\"article:published_time\" content=\"2018-07-22T17:42:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-03-16T12:06:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2024\/01\/csestack-blog.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1280\" \/>\n\t<meta property=\"og:image:height\" content=\"720\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Aniruddha Chaudhari\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@ani_chaudhari\" \/>\n<meta name=\"twitter:site\" content=\"@ani_chaudhari\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Aniruddha Chaudhari\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/\"},\"author\":{\"name\":\"Aniruddha Chaudhari\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"headline\":\"4 Python String Formatting Every Python Developer should Master\",\"datePublished\":\"2018-07-22T17:42:00+00:00\",\"dateModified\":\"2019-03-16T12:06:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/\"},\"wordCount\":561,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"keywords\":[\"Python\",\"python string\"],\"articleSection\":[\"Code\",\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/\",\"name\":\"4 Python String Formatting Every Python Developer should Master\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#website\"},\"datePublished\":\"2018-07-22T17:42:00+00:00\",\"dateModified\":\"2019-03-16T12:06:41+00:00\",\"description\":\"What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/python-string-formatting\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.csestack.org\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"4 Python String Formatting Every Python Developer should Master\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#website\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/\",\"name\":\"CSEstack\",\"description\":\"Computer Science &amp; Programming Portal\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.csestack.org\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\",\"name\":\"Aniruddha Chaudhari\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"contentUrl\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"width\":634,\"height\":634,\"caption\":\"Aniruddha Chaudhari\"},\"logo\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\"},\"description\":\"I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.\",\"sameAs\":[\"https:\\\/\\\/www.csestack.org\",\"https:\\\/\\\/www.facebook.com\\\/aniruddha.ca\",\"pythonwithani\",\"https:\\\/\\\/www.linkedin.com\\\/in\\\/aniruddha28\\\/\",\"https:\\\/\\\/x.com\\\/ani_chaudhari\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCw0a__B0eJsvCujkSIfLTAA\"],\"url\":\"https:\\\/\\\/www.csestack.org\\\/author\\\/anicse\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"4 Python String Formatting Every Python Developer should Master","description":"What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.csestack.org\/python-string-formatting\/","og_locale":"en_US","og_type":"article","og_title":"4 Python String Formatting Every Python Developer should Master","og_description":"What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.","og_url":"https:\/\/www.csestack.org\/python-string-formatting\/","og_site_name":"CSEstack","article_publisher":"https:\/\/www.facebook.com\/aniruddha.ca","article_author":"https:\/\/www.facebook.com\/aniruddha.ca","article_published_time":"2018-07-22T17:42:00+00:00","article_modified_time":"2019-03-16T12:06:41+00:00","og_image":[{"width":1280,"height":720,"url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2024\/01\/csestack-blog.jpg","type":"image\/jpeg"}],"author":"Aniruddha Chaudhari","twitter_card":"summary_large_image","twitter_creator":"@ani_chaudhari","twitter_site":"@ani_chaudhari","twitter_misc":{"Written by":"Aniruddha Chaudhari","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.csestack.org\/python-string-formatting\/#article","isPartOf":{"@id":"https:\/\/www.csestack.org\/python-string-formatting\/"},"author":{"name":"Aniruddha Chaudhari","@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"headline":"4 Python String Formatting Every Python Developer should Master","datePublished":"2018-07-22T17:42:00+00:00","dateModified":"2019-03-16T12:06:41+00:00","mainEntityOfPage":{"@id":"https:\/\/www.csestack.org\/python-string-formatting\/"},"wordCount":561,"commentCount":0,"publisher":{"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"keywords":["Python","python string"],"articleSection":["Code","Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.csestack.org\/python-string-formatting\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.csestack.org\/python-string-formatting\/","url":"https:\/\/www.csestack.org\/python-string-formatting\/","name":"4 Python String Formatting Every Python Developer should Master","isPartOf":{"@id":"https:\/\/www.csestack.org\/#website"},"datePublished":"2018-07-22T17:42:00+00:00","dateModified":"2019-03-16T12:06:41+00:00","description":"What are the different Python string formattings for Python version 2 and 3? Evaluating expression in Python string formatting.","breadcrumb":{"@id":"https:\/\/www.csestack.org\/python-string-formatting\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.csestack.org\/python-string-formatting\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.csestack.org\/python-string-formatting\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.csestack.org\/"},{"@type":"ListItem","position":2,"name":"4 Python String Formatting Every Python Developer should Master"}]},{"@type":"WebSite","@id":"https:\/\/www.csestack.org\/#website","url":"https:\/\/www.csestack.org\/","name":"CSEstack","description":"Computer Science &amp; Programming Portal","publisher":{"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.csestack.org\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218","name":"Aniruddha Chaudhari","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","contentUrl":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","width":634,"height":634,"caption":"Aniruddha Chaudhari"},"logo":{"@id":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg"},"description":"I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.","sameAs":["https:\/\/www.csestack.org","https:\/\/www.facebook.com\/aniruddha.ca","pythonwithani","https:\/\/www.linkedin.com\/in\/aniruddha28\/","https:\/\/x.com\/ani_chaudhari","https:\/\/www.youtube.com\/channel\/UCw0a__B0eJsvCujkSIfLTAA"],"url":"https:\/\/www.csestack.org\/author\/anicse\/"}]}},"_links":{"self":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/3810","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/comments?post=3810"}],"version-history":[{"count":10,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/3810\/revisions"}],"predecessor-version":[{"id":3825,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/3810\/revisions\/3825"}],"wp:attachment":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/media?parent=3810"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/categories?post=3810"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/tags?post=3810"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}