{"id":7224,"date":"2019-04-11T21:59:55","date_gmt":"2019-04-11T16:29:55","guid":{"rendered":"https:\/\/techbeamers.com\/?p=7224"},"modified":"2025-11-30T10:52:42","modified_gmt":"2025-11-30T15:52:42","slug":"python-string-formatting-methods","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/python-string-formatting-methods\/","title":{"rendered":"Different Methods to Format Strings"},"content":{"rendered":"\n<p>String formatting is the process of constructing a string by inserting values into specific locations. With this purpose in mind, we&#8217;ll explore different methods in this quick tutorial. You&#8217;ll get to know which method from the League of format() function, percentage (%), f-strings, center(), or template class to use in <a href=\"https:\/\/techbeamers.com\/python-string-format\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python to format strings<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-python-string-formatting-different-methods\">Python String Formatting Different Methods<\/h2>\n\n\n\n<p>In this tutorial, we will explore five common string formatting methods: f-strings, the <code>str.format()<\/code> method, old-style <code>%<\/code> formatting, the <code>string.Template<\/code> class, and the <code>str.center()<\/code> method. We will also provide a comparison table at the end to help you choose the most suitable method for your specific needs.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"541\" height=\"239\" src=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2019\/04\/Format-or-percentage-for-string-formatting-in-Python.png\" alt=\"Format or percentage for string formatting in Python\" class=\"wp-image-7225\"\/><\/figure>\n<\/div>\n\n\n<p>Let&#8217;s start with the\u00a0<code>%<\/code>\u00a0method and then move on to the others.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-1-using-percentage-to-format-strings\">1. Using Percentage (%) to Format Strings<\/h3>\n\n\n\n<p>The <code>%<\/code> operator is a legacy Python method for string formatting. It works by replacing placeholders in a string with values from a tuple.<\/p>\n\n\n\n<p>If you just have to do some basic string changes, then the operator <code>\u2018%\u2019<\/code> is useful. It will evoke similarities with the C programming language. Here is a basic example to illustrate its usage.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">name = \"Duckworth-Lewis-Stern\"\r\nage = 1997\n\nformatted_string = \"The name method %s was introduced in %d.\" % (name, age)\r\nprint(formatted_string)\n\n# The Duckworth-Lewis-Stern method was introduced in 1997.<\/pre>\n\n\n\n<p>Please note that you need to postfix <code>'%'<\/code> with a type-specific char to indicate the type of data to print. It signifies whether to substitute a number or a string in the formatted message.<\/p>\n\n\n\n<p>The following table shows some of the most common conversion specifiers. You can use these commonly with the <code>\u2018%\u2019<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>Conversion specifier<\/th><th>Description<\/th><\/tr><tr><td><code>s<\/code><\/td><td>String<\/td><\/tr><tr><td><code>d<\/code><\/td><td>Integer<\/td><\/tr><tr><td><code>f<\/code><\/td><td>Floating-point number<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>In case you don&#8217;t specify the integer type value against the &#8216;%d&#8217;, Python will throw the TypeError. The limitation of such a method is that it restricts the type of parameter input.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of <code>%<\/code> Formatting:<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Suitable for developers coming from a C or C++ background.<\/li>\n\n\n\n<li>Can be used in Python 2 and Python 3.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Note<\/h4>\n\n\n\n<p>Do you want to know how to use the&nbsp;<a href=\"https:\/\/techbeamers.com\/python-xor-operator\/\" target=\"_blank\" rel=\"noreferrer noopener\">XOR operator in Python<\/a>? It is a powerful tool for crypto operations such as encryption, generating checksum, and hashing functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-2-using-format-function\">2. Using Format() Function<\/h3>\n\n\n\n<p>The <code>str.format()<\/code> method provides a flexible way to format strings by substituting placeholders with values. This method is available in Python 2 and Python 3, making it a good choice for code that needs to be compatible with both versions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How to use <code>str.format()<\/code><\/h4>\n\n\n\n<p>In a string, you can define placeholders using curly braces <code>{}<\/code>. Then, call the <code>format()<\/code> method on the string and provide the values to be inserted as arguments to the <code>format()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">city = \"New York\"\r\npopulation = 8_400_000\r\naverage_income = 72_000\r\n\r\nformatted_info = \"Welcome to {}, where {} people thrive with an average income of ${} per year.\".format(city, population, average_income)\r\nprint(formatted_info)<\/pre>\n\n\n\n<p>Once you run the above code, it prints the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Welcome to New York, where 8400000 people thrive with an average income of $72000 per year.<\/pre>\n\n\n\n<p>In this example, we&#8217;re formatting a string to display information about a city, its population, and the average income using the <code>str.format()<\/code> method.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of <code>str.format()<\/code><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Provides flexibility in specifying placeholders.<\/li>\n\n\n\n<li>Compatible with both Python 2 and Python 3.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-python-f-string-for-string-formatting\">3. Python F-string for String Formatting<\/h3>\n\n\n\n<p>f-strings are the newest method of string formatting in Python. They first surfaced in Python 3.6 and became the most concise and readable way to format strings.<\/p>\n\n\n\n<p>f-strings work by embedding expressions in curly braces ({}), and the expressions are evaluated at runtime and inserted into the string. For example, the following code clarifies how simple it is to use <a href=\"https:\/\/techbeamers.com\/python-f-string\/\" target=\"_blank\" rel=\"noreferrer noopener\">f-string to format strings in Python<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">name = \"Steve\"\nage = 21\nprofession = \"Software Engineer\"\nprint(f\"{name} is {age} years old, and he is a {profession}.\")<\/pre>\n\n\n\n<p>Furthermore, f-strings can help you format multiple values, and even specify the order of insertion. For example, the following code will print the same string as the previous example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">name = \"Steve\"\r\nage = 21\r\nprofession = \"Software Engineer\"\r\nprint(f\"{0} is {1} years old, and he is a {2}.\")<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of F-Strings:<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Readable and concise syntax.<\/li>\n\n\n\n<li>Supports complex expressions within curly braces.<\/li>\n\n\n\n<li>Available in Python 3.6 and later.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">4. <code>string.Template<\/code> Class<\/h3>\n\n\n\n<p>The <code>string.Template<\/code> is available in the Python template module. It provides a safe and extensible way to perform string substitutions. For instance, it can be useful for creating dynamic strings that reoccur frequently, such as generating HTML pages or emails.<\/p>\n\n\n\n<p>In order to use the <code>Template<\/code> class, you first need to create a template string. Simultaneously, you have to specify the placeholders using dollar signs ($). For example, the following template string contains two placeholders:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from string import Template\r\n\r\nname = \"Ageless\"\r\nage = 'constant'\r\ntemplate = Template(\"I am $name and my immortality is a $age.\")\r\nformatted_string = template.substitute(name=name, age=age)\r\nprint(formatted_string)<\/pre>\n\n\n\n<p>After running the above code, you will get the following output.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">I am Ageless and my immortality is a constant.<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of <code>string.Template<\/code><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Safe against common security issues, such as code injection.<\/li>\n\n\n\n<li>Simple and easy to use for basic string substitutions.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">5. <code>str.center()<\/code> Method<\/h3>\n\n\n\n<p>The method <code>str.center()<\/code> is used for the purpose of center-aligning a string within a given width. While it&#8217;s not a traditional string formatting method, it&#8217;s helpful when you need to align text in a specific way.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How to use <code>str.center()<\/code><\/h4>\n\n\n\n<p>Call the <code>center()<\/code> method on a string, passing the desired width as an argument. The method will pad the string with spaces to center it within the specified width.<\/p>\n\n\n\n<p>For example, the following code will center the string &#8220;Hello, world!&#8221; within a width of 20:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">text = \"Hello, world!\"\r\nprint(text.center(20))<\/pre>\n\n\n\n<p>The above code will print the input text in the center of the given width.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">   Hello, world!    <\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of <code>str.center()<\/code><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Useful for aligning text in specific formatting scenarios.<\/li>\n\n\n\n<li>Simplicity and ease of use.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-comparison-of-python-string-formatting-methods\">Comparison of Python String Formatting Methods<\/h3>\n\n\n\n<p>Now, let&#8217;s compare these string formatting methods to help you choose the most suitable one for your needs:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>Method<\/th><th>Description<\/th><th>Advantages<\/th><th>Disadvantages<\/th><\/tr><tr><td><code>%<\/code>&nbsp;operator<\/td><td>The oldest method of string formatting in Python.<\/td><td>Simple and straightforward.<\/td><td>Not very powerful or flexible.<\/td><\/tr><tr><td><code>.format()<\/code>&nbsp;method<\/td><td>A newer method of string formatting in Python.<\/td><td>More powerful and flexible than the&nbsp;<code>%<\/code>&nbsp;operator.<\/td><td>Can be complex.<\/td><\/tr><tr><td>f-strings<\/td><td>The newest method of string formatting in Python.<\/td><td>Most concise and readable way to format strings.<\/td><td>Not supported in older <a href=\"https:\/\/techbeamers.com\/how-to-check-python-version\/\">versions of Python<\/a>.<\/td><\/tr><tr><td>Template class<\/td><td>Allows you to create template strings with placeholders that can be substituted with actual values.<\/td><td>Useful for creating dynamic strings that are used repeatedly.<\/td><td>Can be complex.<\/td><\/tr><tr><td>Center method<\/td><td>Centers a string within a given width.<\/td><td>Useful for formatting strings for display.<\/td><td>Only formats a single string.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-which-method-should-you-use\">Which Method Should You Use?<\/h2>\n\n\n\n<p>The best method to use for string formatting depends on your specific needs. If you need to format a simple string, then the <code>%<\/code> operator or <code>format()<\/code> method is a good option. If you need to format a string that is used repeatedly, then the <code>Template<\/code> class is a good option. However, in order to center a string within a given width, the <code>center()<\/code> method is a good option.<\/p>\n\n\n\n<p>In summary, if you are using Python 3.6 or higher, then f-strings are the best option for most cases. They are the most concise and readable way to format strings.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>String formatting is the process of constructing a string by inserting values into specific locations. With this purpose in mind, we&#8217;ll explore different methods in this quick tutorial. You&#8217;ll get to know which method from the League of format() function, percentage (%), f-strings, center(), or template class to use in Python to format strings. Python [&hellip;]<\/p>\n","protected":false},"author":321,"featured_media":7225,"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-7224","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\/2019\/04\/Format-or-percentage-for-string-formatting-in-Python.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/7224","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=7224"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/7224\/revisions"}],"predecessor-version":[{"id":23550,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/7224\/revisions\/23550"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/7225"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=7224"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=7224"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=7224"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}