 # Reverse string in Python (All different ways)

## Reverse string in Python (5 different ways)

Python string library does’nt support the in-built “reverse()” as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful. This article discusses several ways to achieve it.

Using loop
 `# Python code to reverse a string ` `# using loop` ` ` `def` `reverse(s):` `  ``str` `=` `""` `  ``for` `i ``in` `s:` `    ``str` `=` `i ``+` `str` `  ``return` `str` ` ` `s ``=` `"Geeksforgeeks"` ` ` `print` `(``"The original string  is : "``,end``=``"")` `print` `(s)` ` ` `print` `(``"The reversed string(using loops) is : "``,end``=``"")` `print` `(reverse(s))`

Output:

```The original string  is : Geeksforgeeks
The reversed string(using loops) is : skeegrofskeeG
```

Explanation : In above code, we call a function to reverse a string, which iterates to every element and intelligently join each character in the beginning so as to obtain the reversed string.

Using recursion
 `# Python code to reverse a string ` `# using recursion` ` ` `def` `reverse(s):` `    ``if` `len``(s) ``=``=` `0``:` `        ``return` `s` `    ``else``:` `        ``return` `reverse(s[``1``:]) ``+` `s[``0``]` ` ` `s ``=` `"Geeksforgeeks"` ` ` `print` `(``"The original string  is : "``,end``=``"")` `print` `(s)` ` ` `print` `(``"The reversed string(using recursion) is : "``,end``=``"")` `print` `(reverse(s))`

Output:

```The original string  is : Geeksforgeeks
The reversed string(using recursion) is : skeegrofskeeG
```

Explanation : In the above code, string is passed as an argument to a recursive function to reverse the string. In the function, the base condition is that if the length of the string is equal to 0, the string is returned. If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.

Using stack
 `# Python code to reverse a string ` `# using stack` ` ` `# Function to create an empty stack. It ` `# initializes size of stack as 0` `def` `createStack():` `    ``stack``=``[]` `    ``return` `stack` `  ` `# Function to determine the size of the stack` `def` `size(stack):` `    ``return` `len``(stack)` `  ` `# Stack is empty if the size is 0` `def` `isEmpty(stack):` `    ``if` `size(stack) ``=``=` `0``:` `        ``return` `true` `  ` `# Function to add an item to stack . It` `# increases size by 1    ` `def` `push(stack,item):` `    ``stack.append(item)` `  ` `# Function to remove an item from stack. ` `# It decreases size by 1` `def` `pop(stack):` `    ``if` `isEmpty(stack): ``return` `    ``return` `stack.pop()` `  ` `# A stack based function to reverse a string` `def` `reverse(string):` `    ``n ``=` `len``(string)` `      ` `    ``# Create a empty stack` `    ``stack ``=` `createStack()` `  ` `    ``# Push all characters of string to stack` `    ``for` `i ``in` `range``(``0``,n,``1``):` `        ``push(stack,string[i])` `  ` `    ``# Making the string empty since all` `    ``# characters are saved in stack    ` `    ``string``=``""` `  ` `    ``# Pop all characters of string and put` `    ``# them back to string` `    ``for` `i ``in` `range``(``0``,n,``1``):` `        ``string``+``=``pop(stack)` `          ` `    ``return` `string` ` ` `# Driver code` `s ``=` `"Geeksforgeeks"` `print` `(``"The original string  is : "``,end``=``"")` `print` `(s)` `print` `(``"The reversed string(using stack) is : "``,end``=``"")` `print` `(reverse(s))`

Output:

```The original string  is : Geeksforgeeks
The reversed string(using stack) is : skeegrofskeeG
```

Explanation : An empty stack is created. One by one characters of string are pushed to stack.
One by one all characters from stack are popped, and put them back to string.

Using extended slice syntax
 `# Python code to reverse a string ` `# using extended slice syntax` ` ` `# Function to reverse a string` `def` `reverse(string):` `    ``string ``=` `string[::``-``1``]` `    ``return` `string` ` ` `s ``=` `"Geeksforgeeks"` ` ` `print` `(``"The original string  is : "``,end``=``"")` `print` `(s)` ` ` `print` `(``"The reversed string(using extended slice syntax) is : "``,end``=``"")` `print` `(reverse(s))`

Output:

```The original string  is : Geeksforgeeks
The reversed string(using extended slice syntax) is : skeegrofskeeG
```

Explanation : Extended slice offers to put a “step” field as [start,stop,step], and giving no field as start and stop indicates default to 0 and string length respectively and “-1” denotes starting from end and stop at the start, hence reversing string.

Using reversed
 `# Python code to reverse a string ` `# using reversed()` ` ` `# Function to reverse a string` `def` `reverse(string):` `    ``string ``=` `"".join(``reversed``(string))` `    ``return` `string` ` ` `s ``=` `"Geeksforgeeks"` ` ` `print` `(``"The original string  is : "``,end``=``"")` `print` `(s)` ` ` `print` `(``"The reversed string(using reversed) is : "``,end``=``"")` `print` `(reverse(s))`

Output:

```The original string  is : Geeksforgeeks
The reversed string(using reversed) is : skeegrofskeeG
```

Explanation : The reversed() returns the reversed iterator of the given string and then its elements are joined empty string separated using join(). And reversed order string is formed.

Last Updated on October 24, 2021 by admin

## Python – Count and display vowels in a stringPython – Count and display vowels in a string

Python | Count and display vowels in a string In this program, we need to count the number of vowels present in a string and display those vowels. This can be done using various methods. In this article, we will

## Convert Text to Speech in PythonConvert Text to Speech in Python

Convert Text to Speech in Python There are several APIs available to convert text to speech in Python. One of such APIs is the Google Text to Speech API commonly known as the gTTS API. gTTS is a very easy

## Python – How to get the last element of listPython – How to get the last element of list

Python | How to get the last element of list List, being an essential python container is used in day-day programming and also in web-development. Knowledge of its operations is necessary. Let’s see all the different ways of accessing the

## Log functions in PythonLog functions in Python

Log functions in Python Python offers many inbuild logarithmic functions under the module “math” which allows us to compute logs using a single line. There are 4 variants of logarithmic functions, all of which are discussed in this article. 1.

## Apply uppercase to a column in Pandas dataframeApply uppercase to a column in Pandas dataframe

When working with data in a Pandas dataframe, you may come across a situation where you need to apply uppercase to a specific column. This can be useful for standardizing data or when you need the column values to be

## Create empty dataframe in PandasCreate empty dataframe in Pandas

The Pandas Dataframe is a structure that has data in the 2D format and labels with it. DataFrames are widely used in data science, machine learning, and other such places. DataFrames are the same as SQL tables or Excel sheets

## How to Convert Floats to Strings in Pandas DataFrame?How to Convert Floats to Strings in Pandas DataFrame?

Convert Floats to Strings in Pandas DataFrame In this post, we’ll see different ways to Convert Floats to Strings in Pandas Dataframe? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from

## Python – Get key from value in DictionaryPython – Get key from value in Dictionary

Python | Get key from value in Dictionary Let’s see how to get the key by value in Python Dictionary. Method 1: Using list.index() The index() method returns index of corresponding value in a list. Below is an implementation how