One place for hosting & domains


      How to Learn Python (Fast & Free)

      There are plenty of resources available that can help you learn Python in no time. From free to paid options, you can find a wide selection of online courses and websites to guide you through the lessons. Using these resources, you can quickly progress from beginner to advanced.

      In this post, we’ll explain what Python is, what it’s used for, and why you might want to learn it. Then we’ll provide you with some of the top places you can go to learn Python as quickly as possible. Let’s jump in!

      An Introduction to Python

      Python is a versatile, high-level, object-oriented programming language that helps you solve problems quickly:

      The Python website

      To give you an idea of how sophisticated and practical this programming language is, consider that some of the biggest brands across the globe have used Python in their projects. These companies include Netflix, Google, and Spotify.

      It’s also a preferred language for many developers. Last year, RedMonk research found that, among developers, Python was the second most popular programming language (behind JavaScript).

      Python 2 and Python 3 are different versions of the open-source Python programming language. However, Python 2 is no longer supported by the Python community. Python 3 is the latest version and is recommended for all new projects.

      What Python Is Used For

      Python is used in many places, including:

      • Web development
      • Scientific computing
      • Data analysis
      • Artificial Intelligence (AI)
      • Machine learning
      • Automation and scripting
      • Software testing and prototyping

      You can also use Python to build all sorts of applications, including web, desktop, and mobile apps. One of the most common use cases for Python is web development, which is the process of building websites and applications.

      Web development can be divided into three parts: front-end development, back-end development, and full-stack development.

      Front-end developers focus on the User Interface (UI) and experience of a website or web app. They use HTML, CSS, and JavaScript to build the Graphical User Interface (GUI).

      Back-end developers focus on the server-side application that powers the front-end GUI. They use languages like Python to write code that runs on a web server. Finally, Full-stack developers are proficient in both front-end and back-end development.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      Why You May Want to Learn Python

      Python is a popular language for web development for many reasons. There are also a variety of benefits to learning it.

      For beginners, Python is relatively easy to learn and has powerful libraries for advanced users. It also has a simple syntax that is simple to read and understand. These features make Python an ideal language for beginners who are just getting started with coding.

      Additionally, the Python language is versatile enough for various purposes. This broad applicability makes it a good choice for developers who want to learn one language that they can use for multiple types of projects.

      It’s also fast. Python code is compiled to bytecode, which is then executed by the Python virtual machine. This compilation step means that Python code runs faster than interpreted languages like PHP and Ruby.

      Another benefit is that Python has powerful libraries that make web development easier. These libraries include Django, Flask, and Bottle. They provide helpful tools for building websites and web apps.

      For example, Django has a module called Django ORM that makes it easy to work with databases in Python. Furthermore, Flask provides a module called flask-restful that makes it easy to build REST APIs.

      Finally, since it’s such a popular programming language, Python also has a robust community to offer support and resources. This means that if you ever run into any Python-related issues or concerns, there will likely be an experienced developer capable of providing a solution.

      What to Learn Before Python

      Technically, you don’t need to know any other programming languages before learning Python. However, mastering different languages can make learning Python easier. If you’re just starting with web development, we recommend taking an introduction to programming course.

      At the very least, it’s best to have a solid grasp of HTML, JavaScript, and CSS. It might also be helpful if you understand the basics of other programming languages such as PHP and JavaScript libraries like React.

      There are two ways to use Python for web development: with or without a framework. A framework is a collection of libraries and tools that make it easier to build a website or web app.

      As we mentioned, the most popular Python frameworks for web development are Django, Flask, and Bottle. We recommend familiarizing yourself with one of these frameworks if you’re just starting.

      If you’re at least moderately experienced with Python, you may want to try developing without a framework. This approach is sometimes called micro-framing because you only use the libraries that you need for your specific project. This method can be faster and easier than using a full-fledged framework like Django or Flask.

      The time it takes to learn Python will depend on your experience level and how much effort you’re willing to invest. Overall, you can learn Python relatively quickly if you can dedicate a few hours each day.

      How to Learn Python Fast (5 Helpful Resources)

      Now that we’ve covered what Python is and its use cases, let’s discuss how you can go about learning it. Here are five helpful resources to get you started!

      1. The Python Website

      The official Python website offers many resources, guides, and tutorials that can introduce you to the basics of programming languages. If you’re starting from ground zero, we recommend the Beginner’s Guide, available under the Docs tab:

      The Python Beginner’s Guide

      This guide is free to access and use. It also provides tons of links to other materials you can utilize throughout your learning journey. In addition to what’s essentially a map for your Python curriculum, you can explore various quizzes and assignments, cheat sheets, style checkers, and other tools. We recommend taking notes to absorb all the information.

      Also available on the Python website is a Developer’s Guide. This resource will be helpful to reference once you’ve mastered the basics and are ready to move to the next level.

      2. Udemy

      Udemy is a popular platform where you can find tons of online learning courses covering a broad range of topics. The website offers both free and paid lessons, including options explicitly geared toward web developers.

      These classes include a free Introduction to Python Programming course that is perfect for beginners:

      The Udemy Intro to Python course

      It consists of one hour and 39 minutes of on-demand video content, covering the basics of Python, including scripts and functions. You can also upgrade to the paid version, which includes a certificate of completion and direct messaging with the instructor.

      When you’re ready to advance, you can enroll in the Python From Beginner to Intermediate in 30 Mins course. This is another free, video-based class that will teach you more sophisticated Python programming concepts.

      3. Codecademy

      Codecademy is a popular and robust online learning platform geared toward developers and programmers. It’s a wonderful resource for exploring and enrolling in classes that cover nearly every topic in data science, web development, IT, and more.

      Although it’s not free, the Pro plan offers a Learn Python 3 course that can serve as an excellent introduction to Python as well as basic programming concepts:

      Codecademy Learn Python 3

      The lessons cover a variety of topics, including:

      • Python syntax
      • Conditionals and control flow
      • Functions
      • Data structures lists and directories
      • And more

      The course doesn’t require any prerequisites. If you sign up for the Pro plan, you will receive a certificate upon completion. Furthermore, the course takes approximately 25 hours to complete.


      If you prefer text-based learning materials, is a solid option:

      The website

      The website is dedicated to helping people of all experience levels learn the programming language and access resources that can simplify the process. It includes both basic and advanced tutorials, covering topics such as:

      • Variables and their types
      • Data science lessons
      • Generators, sets, list comprehensions, function arguments, etc

      The lessons are interactive. You can also find a Facebook group dedicated to the courses where you can discuss the material with other students.

      5. Free Code Camp

      Another platform you can use to find free and paid courses on Python is Free Code Camp. The website has various coding and web development materials, including courses, boot camps, and news.

      Free Code Camp offers a Learning Python: From Zero to Hero course that is free and text-based:

      Free Code Camp Python course

      It explains the basics of Python in simple, easy-to-understand sections. Some of the topics include:

      • How variables, conditional statements, and looping work
      • How to use lists
      • Iterations through data structures
      • Objects and classes

      If you enjoy video-based content, you can also find a YouTube version where the same topics are covered. The video course additionally discusses how to install PyCharm and Python. This course includes four hours and 20 minutes of video content.

      If you complete the beginner course and want to move on to more advanced concepts and projects, you can also participate in the One Month Python Bootcamp. This is a paid course, but the project-based, intensive material is self-paced. It will give you the foundation needed to become a Python developer.

      Start Learning Python Today

      If you’re just getting started with Python, there are many online courses, platforms, and resources you can use (many of which are free!) to help you learn the programming language quickly.

      We recommend beginning with a free introduction course or materials, such as those offered on Once you nail down the basics, you can graduate to more in-depth and specialized teachings offered on third-party and premium platforms.

      Are you looking for an affordable yet reliable hosting solution for your web development projects? Check out DreamHost shared hosting plans to get started!

      Power Your Website with DreamHost

      We make sure your website is fast, secure and always up so your visitors trust you. Plans start at $1.99/mo.

      shared hosting

      Source link

      Reversing a String in Python

      Python supports several common string operations, like
      slicing, indexing, searching,
      advanced formatting
      . However, it lacks a dedicated, built-in method for reversing strings. This guide shows you how to reverse a string in Python by leveraging Python’s tools for working with sequences.

      Before You Begin

      This guide’s example rely on Python 3. Make sure that you have Python 3 installed on your system before getting started.

      You can learn how to install Python 3 from our guide
      How to Install Python 3
      . Be sure to use the drop-down menu at the top of the guide to select the Linux distribution that is compatible with your system.

      How to Reverse a String in Python: 5 Ways

      The sections below include several ways you can reverse strings in Python. While all the possible approaches are not covered, this guide focuses on the most effective and interesting ways to reverse a string in Python.

      Each section’s examples work to reverse a string created using the line below:

      example_string = "doom wolf"

      The string, when reversed, reads “flow mood”.

      Using Slicing

      Python’s slice notation is a powerful tool for manipulating lists and other sequences. You can learn more about Python slices in our guide
      Python Lists and How to Use Them

      Slice notation also extends to strings, where it treats each character in a string as an item in a list. This means you can use the slice notation you would use for reversing a list to reverse a string:

      reversed_with_slice = example_string[::-1]
      flow mood

      You can see the slice notation above in the square brackets. The list below includes a breakdown of how slice notation operates:

      • Slice notation is made up of the following parts:

      • The first colon (:) typically separates the index to begin the slice and the index to end the slice. In the example, these options are left blank to make the slice consist of the whole string.

      • The steps are indicated after the second colon, telling the slice how to progress through the sequence.

        A negative number, has the slice walk backward, starting at the last item in the sequence, and moving through each item until it reaches the beginning.

      Of the methods for reversing a string covered in this guide, slicing is the fastest and takes the least amount of code.

      Reverse a String Using a Loop

      Loops can be used to “manually” reverse a string by iterating through each character. Python provides two kinds of loops you can use: the while loop and the for loop. See our
      For and While Loops in Python 3
      guide for deeper dive into these loop statements.

      While Loop

      A while loop takes a single condition and loops until that condition is no longer met. The standard approach is to then have the condition manipulated, within the loop, to end the loop when it is no longer needed.

      To reverse a string with a while loop, you can use a variable starting at the value of the string’s length. The value should be reduced by one with each iteration of the loop, and the loop should end when the value passes zero. By the end of the loop, the code has walked through each index in the string from the end to the beginning. The Python code below uses a while loop to iterate through the string “doom wolf” and adds the reversed string to the reversed_string variable. The code’s comments include more details on how this is achieved.

      example_string = "doom wolf"
      # Begin with an empty string.
      reversed_string = ""
      # Initialize an index to use for the loop's condition. You need to
      # subtract one from the length, since Python indices start at zero.
      string_working_index = len(example_string) - 1
      # Start a loop that ends when the index gets below zero.
      while string_working_index >= 0:
          # Use the index to add a character from the original string to
          # the reversed string.
          reversed_string += example_string[string_working_index]
          # Reduce the index by one to continue progressing backward
          # through the string.
          string_working_index -= 1
      flow mood

      For Loop

      A for loop takes a sequence and loops through each item in it. You can use it much like the while loop above. However, a more idiomatic approach is shown in the example below. The loop iterates over each character of the original string and adds each one to the beginning of a list. It uses the join() method to convert that list into a string. The code’s comments include more details on how this is achieved.

      example_string = "doom wolf"
      # Begin with an empty list.
      reversed_string_list = []
      # Loop through the characters in the original string.
      for current_character in example_string:
          # Add each character in turn to the beginning of the new list.
          reversed_string_list.insert(0, current_character)
      # Use the join method to create a string from the new list.
      reversed_string = "".join(reversed_string_list)
      flow mood

      The for loop used above is one of the fastest ways to reverse a string using Python. It is second only to the slice method, and it roughly ties with Python’s own reversed() method. The reversed() method is covered
      later on in this guide

      Using Join

      While the join() method is not directly used to reverse a string, it is essential to several of the approaches covered in this guide. Some of the approaches used to reverse a string require that you first convert the string to a list. This is necessary that you have access to several of the list data type’s built-in methods. The join() method is typically used at the end of your code to convert the list back into a string.

      The for loop section above uses the join() method to convert the list into a string after the list items have been reversed. Another example that uses the join() method is displayed below. This example uses the slice approach to reversing a string after converting the string to a list:

      example_string = "doom wolf"
      example_string_list = list(example_string)
      reversed_string_list = example_string_list[::-1]
      reversed_string = "".join(reversed_string_list)
      flow mood

      The join() method’s syntax operates as follows:

      • The empty string ("") at the beginning of "".join(reversed_string_list) is the object that the join method belongs to. This empty string becomes the separator between each element from the list. This new string is then returned and can be stored in a variable.

        So, if you wanted to add a space between each character in the reversed string, you could alter the code above with: " ".join(reversed_string_list).

      • The join method takes a list as an argument. The method then binds each element in the list together using the initial string as a separator. Finally, the method returns the resulting string.

      Using Recursion

      Creating a recursive function is another option for reversing a string. In a recursive function, the function calls itself and then further processes the output. Usually, in this kind of recursive function, each recursive function call gets a smaller, and smaller version of the input. The function keeps calling itself until it reaches the end of the input. When it does, all of the recursive calls’ results collate into a final result.

      This next bit of code shows you what a recursive function for reversing a string can look like:

      def reverse_by_recursion(reversing_string):
          if len(reversing_string) == 0:
              return reversing_string
              return reverse_by_recursion(reversing_string[1:]) + reversing_string[0]

      The above function works in the following way:

      • A condition is created to catch the end of the recursion:

         if len(reversing_string) == 0:
             return reversing_string

        When the input has been worked all the way through, the recursive loop needs to stop and the function needs to return the result.

      • With each iteration, the function calls itself with everything but the first element of the current input:

         return reverse_by_recursion(reversing_string[1:]) + reversing_string[0]

        Functionally, then, each recursive call is dealing with a shorter and shorter version of the original string. Each instance of the function is also stores the first character of its input to add to the end of the new string.

        The first few recursions for the example string look as follows:

         example_string = "doom wolf"
         reverse_by_recursion("oom wolf") + "d"
         reverse_by_recursion("om wolf") + "o"
         reverse_by_recursion("m wolf") + "o"
         reverse_by_recursion(" wolf") + "m"
      • Eventually, the condition len(reversing_string) == 0 is met, and the recursion ends. Working back from the deepest recursion level, the results recombine to form the new reversing_string.

        For the example string, the process of this working back looks something like this:

         "f" + "l" + "o" + "w" + " " + "m" + "o" + "o" + "d"

      While not the fastest of the approaches covered in this guide, the recursive function has the advantage of following functional programming principles.


      The Python interpreter enforces a limit to the number of recursions (or recursion depth) a function can have. By default, the limit is 1,000.

      This is because, unlike some other language compilers (like those for C/C++ and Scala), the Python interpreter does not have tail-call recursion optimization.

      Essentially, this means that Python can experience incredibly high processing demands when the number of recursions gets too large.

      Using the reversed() Method

      Another approach to reversing a string is to use Python’s built-in reversed() method. This method takes a list or other sequential object — like a string — and returns an iterable object in reverse.

      The example below uses the method on the example_string variable, and then uses the join() method discussed above to convert the returned iterable into a string.

      example_string = "doom wolf"
      # Assign the returned iterable to a variable.
      reversed_iterator = reversed(example_string)
      # Put the elements of the iterable together as a string, using
      # a blank string ("") as the separator for each character.
      reversed_string = "".join(list(reversed_iterator))
      flow mood

      Though not quite as fast as using slice and a bit more verbose, the reversed() method provides a convenient ready-made solution.
      Aside from the slicing approach, the reversed() method is faster than the other ways used to reverse a string in this guide.

      Using a Custom Function

      In the
      Using Recursion
      section, a custom function is used to reverse a string. In fact, you can use a custom function for any of the approaches outlined in this guide.

      Creating a dedicated function for reversing a string can be convenient when you want to use the same approach in multiple places. This is especially the case when you are using a more complicated approach, like the while or for loop.

      The function defined below demonstrates how useful a custom function can be. The function takes a string as input and reverses it using the slice approach.

      The function also includes an optional parameter — reversal_style. Adjusting this parameter, you can have the function reverse the string with a loop or the reversed() method instead of a slice.

      As another bonus, the function also includes a condition to reverse the string word-by-word, rather than character-by-character:

      def reverse_string_my_way(string_in, reversal_style="slice"):
          # Use a for loop if indicated by reversal_style.
          if reversal_style == "loop":
              string_out_list = []
              for item in string_in:
                  string_out_list.insert(0, item)
              string_out = "".join(string_out_list)
          # Use the reversed function if indicated by reversal_style.
          elif reversal_style == "reversed":
              reversed_iterator = reversed(string_in)
              string_out = "".join(list(reversed_iterator))
          # Reverse the order of words, rather than characters, in
          # the string if indicated by reversal_style.
          elif reversal_style == "word":
              word_list = string_in.split(" ")
              word_list = word_list[::-1]
              string_out = " ".join(word_list)
          # By default, use the slice approach to reverse the string.
              string_out = string_in[::-1]
          return string_out
      print(reverse_string_my_way(example_string)) # Uses the slice approach.
      print(reverse_string_my_way(example_string, "loop")) # Uses a for loop.
      print(reverse_string_my_way(example_string, "word")) # Reverses the order of words.
      flow mood
      flow mood
      wolf doom


      There are many ways to reverse a string in Python. However, some approaches are more efficient than others and which you choose depends on your own needs. For example, if execution speed is a concern, you should use slicing, since it is the fastest. You can also create a custom function that employs looping if you’d like to reuse the function throughout your code. If you’re not as concerned with performance, you may choose to use a recursive function.

      If you’de like to learn more about Python, take a look through our other
      Python guides and tutorials

      Source link

      An Introduction to Python String Interpolation

      During string interpolation a string literal is evaluated and if any placeholders are present, they are substituted by the indicated variable values. String interpolation helps reduce repetition in code and allows for dynamic string substitution. Python string interpolation consists of two parts: a string template and a value, or set of values, that you want to place within that template. To trigger string interpolation, the compiler needs some method of determining where to place the values within the string template. Python provides four techniques to do this, and this guide covers them all. Each string interpolation technique has its own advantages and disadvantages. The four ways to trigger string interpolation are the following:

      • A modulo character (%) placed within a string literal indicates where to make the string replacement and can be followed by string format indicators and variable names that store replacement values.
      • Call the .format() method on your string literal. Use a pair of curly braces ({}) to indicate where to make the string replacement. The .format() method’s arguments indicate the values to use for the string replacement.
      • Precede any string literal by the letter f to use formatted string literals, also referred to as “f-strings”. The string literal can contain curly braces ({}) that delimit a python expression and variables to use for the string substitution.
      • Import the
        String module’s Template class
        into your Python code. Store your string template in a variable using the Template() class. Then, use the Template class’ .substitute() function to indicate which values to use in the string substitution.

      The sections below cover each of the four ways you can use string interpolation in Python.

      The String Modulo Operator and String Formatting

      If code readability is a top concern, the modulo operator (%) method for string interpolation and formatting is a good choice. Its syntax is more concise compared to other string interpolation methods, because it does not require as many formatting arguments. The modulo operator is, however, the least flexible of the methods available for string interpolation. It is also an older string formatting method that may not remain supported as newer versions of Python are released. If you are working with an older Python codebase that uses the string modulo operator, then you may need to become familiar with its syntax.

      The general syntax for string formatting with the string modulo operator is the following:

      %[flags][width][.precision]format_indicator %(values)

      Using String Format Indicators

      String formatting with the modulo operator includes the % character and a format indicator for each of the entries in the string template. A format indicator converts a provided value into the type indicated by the format indicator. The conversion is done before the value is inserted into the string. Python provides the following format indicators:

      • %s: String (performed using the str() function)
      • %d: Integer
      • %f: Floating point
      • %e: Lowercase exponent
      • %E: Uppercase exponent
      • %x: Lowercase hexadecimal
      • %X: Uppercase hexadecimal
      • %o: Octal
      • %r: Raw (performed using the repr() function)
      • %g: Floating point for smaller numbers, lowercase exponent for larger numbers
      • %G: Floating point for smaller numbers, uppercase exponent for larger numbers
      • %a: ASCII (performed using the ascii() function)
      • %c: Converts an int or a char to a character, such as 65 to the letter A

      The values to use for string substitution are placed after another % outside of the string literal. They can appear alone when working with a single value, or within a tuple when working with multiple values. You can use arithmetic calculations to generate a string replacement value, as demonstrated in the example below.

      myVal1 = 10.1
      myVal2 = 2.2
      print("The sum of %s and %s is %s." %(my_val_1, my_val_2, my_val_1+my_val_2))
      print("The sum of %d and %d is %d." %(my_val_1, my_val_2, my_val_1+my_val_2))
      print("The sum of %f and %f is %f." %(my_val_1, my_val_2, my_val_1+my_val_2))
      print("The sum of %e and %e is %E." %(my_val_1, my_val_2, my_val_1+my_val_2))
      print("The sum of %x and %x is %X." %(int(my_val_1), int(my_val_2),
      print("The sum of %o and %o is %o." %(int(my_val_1), int(my_val_2),

      The output shows the result of the various format indicators.

      The sum of 10.1 and 2.2 is 12.3.
      The sum of 10 and 2 is 12.
      The sum of 10.100000 and 2.200000 is 12.300000.
      The sum of 1.010000e+01 and 2.200000e+00 is 1.230000E+01.
      The sum of a and 2 is C.
      The sum of 12 and 2 is 14.

      The format indicators in the first print() statement convert my_val_1, my_val_2, and my_val_1+my_val_2 into strings. The string values are then substituted where the % character is placed within the string literal. The subsequent format indicator examples perform similar substitutions, but instead convert the values to decimals, floating point numbers, exponents, hexadecimal numbers, and octal numbers. Notice that you must convert floating-point values to integer values when working with the %x, %X, or %o format indicators. This is why the int() method is used in the last two print() statements.

      The following code shows the difference between string output and raw output for the same variable value:

      my_val="Hello There!"
      print("%s, it's a lovely day!" %my_val)
      print("%r, it's a lovely day!" %my_val)

      When working with raw output, the compiler doesn’t interpret any of the characters and displays every character that is present in your string. This allows you to use special characters as needed. The second print() statement made use of the raw output format indicator (%r), so the output displays the opening and closing single quotes.

      Hello There!, it's a lovely day!
      'Hello There!', it's a lovely day!

      Using Flags to Modify Output

      The string modulo operator supports flags that further control a string’s formatting. The following examples demonstrate the usage of flags in modulo string formatting.

      The examples below use the variables, my_val_1 and my_val_2 to store the values to embed within the example strings.

      my_val_1 = 10.1
      my_val_2 = 2.2

      The format indicator %5d, uses the 5 flag to indicate that the integers should be formatted with 5 spaces. Since the d portion converts the floating-point numbers to integers, three spaces are placed in front of the integers.

      print("%5d %5d" %(my_val_1, my_val_2))
      10     2

      Similarly, you can pad your output with zeros:

      print("%05d %02d" %(my_val_1, my_val_2))
      00010 02

      To left justify your integers, use the - flag with your string formatting:

      print("%-5d %-5d" %(my_val_1, my_val_2))
      10    2

      It’s possible to achieve more sophisticated formatting using the modulo operator. For example, you can format a floating-point value to have a specific number of digits after the decimal point. You can also add a dollar sign to monetary values. The following code shows both methods.

      print("%07.2f" %my_val_1)
      print("$%1.2f" %my_val_1)

      In the first example, the first part of the format specifier tells the compiler to make the entirety of the output seven digits long (%07). The second part of the format specifier tells the compiler to keep the part after the decimal point limited to two digits (2f). The second example uses a value of one for the entirety of the output, but limits the decimal output to two digits. When you specify a length that can’t possibly hold the entire value, Python still displays the whole value as shown.

      The Python String .format() Method and Positional Arguments

      Python’s str.format() method provides another option for working with string formatting and interpolation. With the str.format() method, it’s possible to obtain any string output you need, however, it may require complex code. Due to its complexity, the .format() method may not always be the best choice. Formatting characters can prove difficult to read and even harder to troubleshoot.

      The str.format() method can be called on any Python string object. Replacement fields are surrounded by curly braces ({}). A replacement field contains the name of a
      keyword argument
      or the numeric index of a positional argument.

      The example below demonstrates using the str.format() with replacement fields and a named keyword argument.

      'My name is {name} and I am {age} years old'.format(name="Frida", age=114)

      The Python interpreter returns the original string. However, the replacement fields are expanded to display the values of the .format() method’s keyword arguments.

      'My name is Frida and I am 114 years old'

      The next example demonstrates using the str.format() with replacement fields and the numeric index of a positional argument.

      'My name is {0} and I am {1} years old'.format('Frida', 114)

      The Python interpreter returns the original string. In this case, the replacement fields are expanded to display the values of the str.format() method’s positional arguments.

      Similar to the modulo method of string formatting, you can use format indicators with your str.format() method’s arguments to further modify your string output. For example, the two variables, my_val_1 and my_val_2 store floating-point numbers.

      my_val_1 = 10.1111
      my_val_2 = 2.2222

      Use the str.format() method and format indicators to adjust the number of digits that are displayed after the decimal point.

      'The first value equals {:.2f} and the second value equals {:.3f}.'.format(my_val_1, my_val_2)

      Python returns the following formatted string:

      'The first value equals 10.11 and the second value equals 2.222.'

      The format indicator {:.2f} specifies that the floating-point value should display two places after the decimal point. While the format indicator {:.3f}, specifies that the floating-point value should display three places after the decimal point.

      The str.format() method supports many format indicators that align your output, and adjust the
      presentation type for string, integer, float, and decimal values

      Python f-strings

      Another way to format strings is with Python f-strings, also known as formatted string literals. As with the other string formatting techniques discussed in this guide, f-strings can contain replacement fields denoted with curly braces ({}). When compared to the str.format() method, the f-string method produces simpler and more readable code. In addition, f-strings are more performant than the modulo operator or the str.format() method.

      When using a Python f-string, you must prefix your string literal with f or F. For example:

      import datetime
      f'The date today is { %d, %Y}'

      The Python interpreter returns the following string:

      'The date today is March 01, 2022'

      The replacement field includes a Python expression and a date format specifier. To achieve the same result using the str.format() method, you need the following code:

      import datetime
      'The date today is {:%B %d, %Y}'.format(

      The f-string version of the code is more succinct and readable than the str.format() version. Similar to str.format(), you should refer to Python’s
      Format Specification Mini-Language documentation
      to learn all the ways that you can format strings using f-strings.

      Python Template Strings

      The Python 3
      Template Class
      is part of the String module. Compared to the other methods described in this guide, template strings provide simpler string substitution. However, it does not support string formatting, like f-strings, str.format(), and the string modulo operator. While this makes Template class strings less powerful, they are considered more secure. For this reason, the Template class is a good choice if you are working with user-generated strings.

      String substitutions are indicated using a $ interpolation character. The $ should be followed by the name of a dictionary key that has been passed as an argument to the Template class’s substitute() method. The substitute() method requires a dictionary-like object with keys as its argument. The Template() class accepts the template string as its argument. The example below imports the Template class, stores a new instance of the Template class and the string template in a variable. The new Template class’ substitution() method is called and it contains the substitution string to use.

      from string import Template
      greeting = Template('Welcome, $name')

      The Python interpreter returns the interpolated string:

      'Welcome, Frida!'

      The Python 3 Template class provides more readable code, especially when using a single template with various values stored in a
      . For example:

      File: ~/home/username/
      from string import Template
      names = []
      names.append(dict(first='Anais', last='Nin'))
      names.append(dict(first='Octavia', last='Butler'))
      names.append(dict(first='Frida', last='Kahlo'))
      greeting = Template('Welcome, $first $last')
      for name in names:

      When you run the above Python file, the following interpolated strings are returned as output:

      Welcome, Anais Nin
      Welcome, Octavia Butler
      Welcome, Frida Kahlo

      The code in the file is straightforward and readable. You can see that the template to be used derives its substitution values from the dictionaries appended to the names list. Then, a concise for loop, calls the template, and uses the substitute() method to perform the template substitutions.


      Python provides multiple ways to format strings, each with its own advantages and disadvantages. The method you choose depends on your particular use case and your familiarity with each method. Overall, the f-string method provides a good combination of formatting power and readable code. However, you may consider the str.format() method or the Template string class if maintaining security with user-generated strings is a concern. Finally, the string modulo operator is a legacy method for string substitution and formatting. But, it is helpful to familiarize yourself with this method if you are working with a legacy Python codebase.

      Source link