Last Updated:

How do I flip a string in Python?

 

A Python string is a set of Unicode characters. Python has many functions for manipulating strings, but the Python string library does not support the built-in "reverse()" function. But there are various ways to reverse the line.

Methods for reversing a Python string:

  1. Using a for loop
  2. Using a while loop
  3. Using the slice operator
  4. Using the reversed() function
  5. Using recursion()

Using a for loop

An example of a reverse of a given string, using a for loop:

defreverse_string(str):
str1="" # Declaring an empty string to store an inverted foriinstr string
:
str1 = i + str1
returnstr1 # It will return to the back line in the caller function
str = "JavaTpoint"# of the specified print string
("source string: ",str)
print("back line", reverse_string(str))# call function

Result:

('Source line: ','JavaTpoint')
("Reverse line", "tniopTavaJ")

Explanation:

In the above code, we declared the reverse_string() function and passed the str argument. In the body of the function, we declared an empty string variable str1, which will contain an inverted string.

The for loop then repeats each element of that string, appends each character at the beginning, and stores it in the str1 variable. After completing the iteration, it returned in reverse order of str1 strings and looks like this in the calling function.

Using recursion()

The string can also be flipped using recursion(). Recursion is the process in which a function calls itself. Consider the following example.

Example:

# flip line
# using defreverse(str) recursion
:
iflen(str) == 0: # Checking the length of the string
returnstr
else:
return reverse(str[1:]) + str[0]
str = "Devansh Sharma"
print("source string: ", str)
print(the reverse line(using recursion is : "reverse(str)")

Result:

('Source string : ', 'JavaTpoint')
('Inverted line(using reversed):', 'tniopTavaJ')

Explanation:

In the code above, we defined a function that takes a string as an argument.
In the body of the function, we defined a basic recursion condition — if the string length is 0, then the string is returned, and if not, then we call the function recursively.