One place for hosting & domains


      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

      split() String Method in JavaScript

      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Sometimes you just need to take strings apart:

      var sentence = "Oh a cookie!"
      sentence.split(" ");
      // [ "Oh", "a", "cookie!" ]


      The trick is using the correct separator:


      Common use case

      If you leave the separator blank, it will dissect each character.

      var pieces = sentence.split("");
      // [ "O", "h", " ", "a", " ", "c", "o", "o", "k", "i", "e", "!" ]

      Notice that the spaces stay in the resulting array because they were not used as the separator.

      Learn More

      split() is just one of several methods that help developers work with strings, to learn more see How To Index, Split, and Manipulate Strings in JavaScript

      Source link