Sling Academy
Home/Python/Python: 5 Ways to Reverse a String

Python: 5 Ways to Reverse a String

Last updated: May 24, 2023

When writing code with Python, there might be cases where you need to reverse a string, such as when you want to check if a string is a palindrome ( a word or phrase that is the same when read forward or backward) or perform some encryption or decryption algorithms. This succinct, practical article will show you several different approaches to reversing a given string in Python.

Using the slice notation with a step of -1

This approach uses the slice notation [start:end:step] to reverse the string by specifying a step of -1.

Example:

text = "ABCDE 12345"
reversed_text = text[::-1]

print(reversed_text)

Output:

54321 EDCBA

Using the reversed() function and the join() method

The reversed() function takes a string and returns an iterator that traverses the string in reverse order. From the resulting iterator, you can use ''.join() to obtain the reversed string.

Example:

text = "Sling Academy"
reversed_text = ''.join(reversed(text))

print(reversed_text)

Output:

ymedacA gnilS

Using a for…in loop

In this approach, we will use a for...in loop to iterate over each character in the original string and builds the reversed string by prepending each character.

A code example is worth more than a thousand words:

text = "ABCDEFGH"
reversed_text = ''
for char in text:
    reversed_text = char + reversed_text

print(reversed_text)

Output:

HGFEDCBA

Using recursion

In the example below, we will define a recursive function named reversed_string to reverse an input string by appending the last character to the reversed substring of the remaining characters.

Example:

def reverse_string(text):
    if len(text) <= 1:
        return text
    return reverse_string(text[1:]) + text[0]

reversed_text = reverse_string("Welcome to Sling Academy!")

print(reversed_text)

Output:

!ymedacA gnilS ot emocleW

Using the list.reverse() method

In this approach, we will convert the original string into a list, then reverse the list by using the reverse() method. Finally, we will convert it back to a string with the help of the str.join() method.

The code:

text = "Elden Ring is a great game!"
char_list = list(text)
char_list.reverse()
reversed_text = ''.join(char_list)

print(reversed_text)

Output:

!emag taerg a si gniR nedlE

Next Article: Python: 8 Ways to Concatenate Strings

Previous Article: 4 Ways to Format a String in Modern Python

Series: Working with Strings in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots