Reverse word in python

Since everyone else’s covered the case where the punctuation moves, I’ll cover the one where you don’t want the punctuation to move.

import re
def reverse_words(sentence):
    return re.sub(r'[a-zA-Z]+', lambda x : x.group()[::-1], sentence)

Breaking this down.

re is python’s regex module, and re.sub is the function in that module that handles substitutions. It has three required parameters.

The first is the regex you’re matching by. In this case, I’m using r'w+'. The r denotes a raw string, [a-zA-Z] matches all letters, and + means «at least one».

The second is either a string to substitute in, or a function that takes in a re.MatchObject and outputs a string. I’m using a lambda (or nameless) function that simply outputs the matched string, reversed.

The third is the string you want to do a find in a replace in.

So «What is my name?» -> «tahW si ym eman?»

Addendum:

I considered a regex of r'w+' initially, because better unicode support (if the right flags are given), but w also includes numbers and underscores. Matching - might also be desired behavior: the regexes would be r'[a-zA-Z-]+' (note trailing hyphen) and r'[w-]+' but then you’d probably want to not match double-dashes (ie --) so more regex modifications might be needed.

The built-in reversed outputs a reversed object, which you have to cast back to string, so I generally prefer the [::-1] option.

We are given a string and we need to reverse words of a given string

Examples:

Input : str =" geeks quiz practice code"
Output : str = code practice quiz geeks  
Input : str = "my name is laxmi"
output : str= laxmi is name my 

reverse the words in the given string program 

Python3

string = "geeks quiz practice code"

s = string.split()[::-1]

l = []

for i in s:

    l.append(i)

print(" ".join(l))

Output

code practice quiz geeks

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string

We are given a string and we need to reverse words of a given string? Examples:

Input : str = geeks quiz practice code
Output : str = code practice quiz geeks

This problem has an existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem.

  • Separate each word in a given string using split() method of string data type in python.
  • Reverse the word separated list.
  • Print words of the list, in string form after joining each word with space using ” “.join() method in python.

Implementation:

Python3

def rev_sentence(sentence):

    words = sentence.split(' ')

    reverse_sentence = ' '.join(reversed(words))

    return reverse_sentence

if __name__ == "__main__":

    input = 'geeks quiz practice code'

    print (rev_sentence(input))

Output

code practice quiz geeks

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string

This solution use the same procedure but have different methods to reverse the words in string with the help backward iteration and regular expression module. Following are the steps of our approach:

  • Find all the words in string with the help of re.findall() function. 
  • Iterate over the list in backward manner. 
  • Join the words in a string with the help of join() function.

Python3

import re

def rev_sentence(sentence):

    words = re.findall('w+', sentence)

    reverse_sentence = ' '.join(words[i] for i in range(len(words)-1, -1, -1))

    return reverse_sentence

if __name__ == "__main__":

    input = 'geeks quiz practice code'

    print (rev_sentence(input))

Output

code practice quiz geeks

Another approach to reverse the words in a given string is to use a stack. A stack is a data structure that supports push and pop operations. You can use a stack to reverse the words in a string by pushing the words onto the stack one by one and then popping them off the stack to form the reversed string.

Here is an example of how you can use a stack to reverse the words in a given string in Python:

Python3

string = "geeks quiz practice code"

stack = []

for word in string.split():

    stack.append(word)

reversed_words = []

while stack:

    reversed_words.append(stack.pop())

reversed_string = " ".join(reversed_words)

print(reversed_string)

Output

code practice quiz geeks

Method: 

1. The input string is split into a list of words using the split() method. By default, split() splits the string on whitespace characters (spaces, tabs, and newlines), so each word is separated into its own element of the list.

2. An empty string variable called reversed_string is initialized.

3. A for loop is used to iterate over the indices of the words list in reverse order. The loop starts from the index of the last word in the list (i.e., len(words)-1) and goes backwards to the first word (i.e., index 0). For each index, the corresponding word is appended to reversed_string, followed by a space character.

4. Finally, the extra space character at the end of reversed_string is removed using the strip() method, and the resulting string is returned.

Python3

def reverse_words(string):

    words = string.split()

    reversed_string = ''

    for i in range(len(words)-1, -1, -1):

        reversed_string += words[i] + ' '

    return reversed_string.strip()

string = "geeks quiz practice code"

reversed_string = reverse_words(string)

print(reversed_string) 

Output

code practice quiz geeks

time complexity: O(n)  

auxiliary space: O(n)

This approach has a time complexity of O(n) and a space complexity of O(n), where n is the length of the string.

Reverse Words in a String Using Two-Pointer Approach

  1. Reverse the entire string.
  2. Reverse each word in the reversed string.

Steps:

  1. Start by taking the input string as s.
  2. Reverse the entire string s using a two-pointer approach.
  3. Initialize two pointers, start and end, both pointing to the first character of the reversed string respectively.
  4. Traverse the string s and when a space is encountered, reverse the word between start and end pointers using a similar two-pointer approach.
  5. Update the start pointer to the next character after the space and the end pointer to the same position as the start pointer.
  6. Repeat steps 4 and 5 until the end of the string is reached.
  7. Return the reversed string.

Python3

def reverse_word(s, start, end):

    while start < end:

        s[start], s[end] = s[end], s[start]

        start += 1

        end -= 1

def reverse_string(s):

    s = list(s)

    start, end = 0, len(s) - 1

    reverse_word(s, start, end)

    start = end = 0

    while end < len(s):

        if s[end] == ' ':

            reverse_word(s, start, end - 1)

            start = end + 1

        end += 1

    reverse_word(s, start, end - 1)

    return ''.join(s)

S = "geeks quiz practice code"

print(reverse_string(S))

Output

code practice quiz geeks

Time Complexity: O(N), where N is the length of the input string.

Auxiliary Space: O(1), the algorithm uses constant space to perform the reverse operation in place.

This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Knowing how to reverse a Python string is a common thing you might have to do as a Python developer. It could also help you in coding interviews.

Python does not provide a built-in function to reverse the characters in a string. To reverse a string in Python you can use the slice operator with the syntax [::-1]. You can also use the reversed() function together with the string join() function.

Let’s go through different ways to return a Python string in reverse order.

Let’s immediately learn a simple method to reverse a string.

I want to give you the solution to the problem first, then we will understand how this solution exactly works.

Open the Python shell and define a Python string:

>>> word = "Python"

To reverse a string in Python you can use slicing with the following syntax: [::-1].

>>> print(word)
Python
>>> print(word[::-1])
nohtyP 

Fantastic! Nice and concise!

As you can see in the second print statement the reversed string is returned.

If you want to make this code reusable you can create a function that given a string returns the reversed string.

>>> def reverse_word(word):
...     return word[::-1]
... 
>>> print(reverse_word("Python"))
nohtyP 

In the next section, we will learn how the expression [::-1] works.

What is the Meaning of [::-1] in Python?

You might be wondering, what does the syntax [::-1] mean?

This is the Python slice operator that in its basic form allows to select a substring from a string.

For example, let’s say you want to select the first three characters of our word, you can use the following slicing expression.

>>> print(word[0:3])
Pyt

The substring starts at the character with index 0 (the first character) and ends at the character with index 3 – 1 so 2.

If we omit the first zero in the slice expression the output is the same:

>>> print(word[:3])
Pyt 

But, the slicing syntax we have used before is slightly different:

[::-1]

This expression uses the extended syntax for the slice operator.

[begin:end:step]

By default, the value of step is 1. Also if you don’t specify any value for begin the Python interpreter will start from the beginning of the string.

And, if you don’t specify a value for end Python will go until the end of the string.

Let’s see what happens if we don’t specify a value for begin and end and we set the step to 1:

>>> print(word)
Python
>>> print(word[::1])
Python 

Python goes through every character of the string from the beginning to the end using a step equal to 1.

The only difference in the expression we have seen before to reverse a string is that we have used a step equal to -1.

When you specify a step equal to -1 in a slicing expression the Python interpreter goes through the characters of the string backward. This explains the output returned by the expression [::-1].

>>> print(word[::-1])
nohtyP 

How Do You Reverse a String with a Python While Loop?

We can obtain the same output returned by the slice operator but using a while loop.

This is not something you would necessarily use if you had to reverse a string in a real application considering that it requires more lines of code compared to slicing.

At the same time knowing how to reverse a string in Python with a while loop helps you develop the way you think when you look for a solution to a coding problem.

Here is what we want to do…

Start from the end of our input string and go backward one character at a time using a while loop.

Every character is added to the new string reversed_word which is initially an empty string and at the end contains the original string but reversed.

def reversed_word(word):
    reversed_word = ''
    index = len(word) - 1

    while index >= 0:
        reversed_word += word[index]
        index -= 1

    return reversed_word

As you can see we start at the index len(word) -1, the last character of our string. Then we go back, at every iteration of the while loop, as long as the index is greater than or equal to zero.

Remember that len(word) is the length of the string.

Note: writing index -= 1 is the same as index = index – 1. So it’s just a more concise way to decrement the index by 1.

Let’s test this program by calling our function:

print(reversed_word("Python"))

[output]
nohtyP 

It works fine!

What Does the Python reversed() Function Do?

Python also provides a built-in function called reversed().

What does it do? Can we use it to reverse the characters in a string?

According to the official Python documentation, the reversed() function returns a reverse iterator.

But, how can it help?

Reversed function in Python

>>> print(reversed("Greece"))
<reversed object at 0x7ff8e0172610> 

Here is what we get if we cast the reverse iterator to a list.

>>> print(list(reversed("Greece")))
['e', 'c', 'e', 'e', 'r', 'G'] 

We get back a Python list in which every element is a character of the initial string but in reversed order. To obtain the reversed string we also have to use the string join() function.

>>> print(''.join(reversed("Greece")))
eceerG 

We are using an empty separator character to concatenate the characters returned by the reverse iterator.

We could also cast the iterator to a list before passing it to the join function and the result would be the same.

>>> print(''.join(list(reversed("Greece"))))
eceerG 

We have seen how to reverse a string in Python using just one line of code.

In one of the final sections of this tutorial, we will analyze which approach is the most performant.

Reverse String in Python Using Recursion

In this section, we will create a Python function that uses recursion to reverse a word / string.

This is a more complex implementation you will probably never use, but understanding it can add something to your Python developer knowledge.

def reverse_string_recursively(word):
    if len(word) == 0:
        return word
    else:
        return reverse_string_recursively(word[1:]) + word[0]

Let’s break down this code to understand how it works.

Call the function as shown below:

print(reverse_string_recursively('Hello'))

The first time it’s executed, the return statement in the else branch is equal to:

reverse_string_recursively('ello') + 'H'

This expression is equal to:

reverse_string_recursively('llo') + 'e' + 'H'

And this continues until the string passed to the function is empty:

reverse_string_recursively('lo') + 'l' + 'e' + 'H'
reverse_string_recursively('o') + 'l' + 'l' + 'e' + 'H'
reverse_string_recursively('') + 'o' + 'l' + 'l' + 'e' + 'H'

When the length of the string passed to the function is zero the function returns the string itself (see the logic in the if branch), so the final result is:

'' + 'o' + 'l' + 'l' + 'e' + 'H'

Here is what you get if you execute the expression above in the Python shell:

>>> '' + 'o' + 'l' + 'l' + 'e' + 'H'
'olleH'

The + sign is the Python string concatenation operator.

How to Reverse a Unicode String

Unicode is a standard used to represent characters in any language (and not only, with Unicode you can even represent emojis).

You might want to use Unicode if you have to handle strings in languages other than English.

For example, the following word means ‘Good morning’ in Greek:

Καλημερα

Let’s print each letter by using their Unicode representation:

>>> print('U0000039A')
Κ
>>> print('U000003B1')
α
>>> print('U000003BB')
λ
>>> print('U000003B7')
η
>>> print('U000003BC')
μ
>>> print('U000003B5')
ε
>>> print('U000003C1')
ρ
>>> print('U000003B1')
α  

And now let’s print the full word still using the Unicode representation for each character:

>>> word = 'U0000039AU000003B1U000003BBU000003B7U000003BCU000003B5U000003C1U000003B1'
>>> print(word)
Καλημερα 

We can reverse the string by using the first approach we have covered in this tutorial (the slice operator).

>>> print(word[::-1])
αρεμηλαΚ 

Performance Comparison of Approaches to Reverse a Python String

Let’s confirm which one of the approaches to reverse the characters of a string is the fastest.

To measure the performance of each implementation we will use Python’s timeit module.

Reverse a string using the slice operator

import timeit 

testfunction = '''
def reversed_word():
    return 'hello'[::-1]
'''

print(timeit.timeit(testfunction))

[output]
0.054680042 

Reverse a string using a while loop

import timeit 

testfunction = '''
def reversed_word():
    word = 'hello'
    reversed_word = ''
    index = len(word) - 1

    while index >= 0:
        reversed_word += word[index]
        index = index - 1

    return reversed_word
''' 

print(timeit.timeit(testfunction))

[output]
0.063328583  

Reverse a string using the join() and reversed() functions

import timeit 

testfunction = '''
def reversed_word():
    word = 'hello'
    return ''.join(reversed(word))
''' 

print(timeit.timeit(testfunction))

[output]
0.062542167 

Reverse a string using the join(), list() and reversed() functions

import timeit 

testfunction = '''
def reversed_word():
    word = 'hello'
    return ''.join(list(reversed(word)))
''' 

print(timeit.timeit(testfunction))

[output]
0.059792666999999994  

The fastest implementation is the one using the slice operator.

Conclusion

In this tutorial, we have seen multiple ways to reverse a Python string.

The most performant way to reverse a string uses slicing but it’s also possible to use the reversed() function together with the join() and list() functions.

Implementing your own function to reverse a string using a loop doesn’t really make sense considering that it wouldn’t be as performant as the slice operator and it would require more lines of code.

Bonus read: Are you getting started with Python? Have a look at this tutorial that will give you a comprehensive overview of what it means to start coding in Python.

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

When you’re using Python strings often in your code, you may face the need to work with them in reverse order. Python includes a few handy tools and techniques that can help you out in these situations. With them, you’ll be able to build reversed copies of existing strings quickly and efficiently.

Knowing about these tools and techniques for reversing strings in Python will help you improve your proficiency as a Python developer.

In this tutorial, you’ll learn how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Use iteration and recursion to reverse existing strings manually
  • Perform reverse iteration over your strings
  • Sort your strings in reverse order using sorted()

To make the most out of this tutorial, you should know the basics of strings, for and while loops, and recursion.

Reversing Strings With Core Python Tools

Working with Python strings in reverse order can be a requirement in some particular situations. For example, say you have a string "ABCDEF" and you want a fast way to reverse it to get "FEDCBA". What Python tools can you use to help?

Strings are immutable in Python, so reversing a given string in place isn’t possible. You’ll need to create reversed copies of your target strings to meet the requirement.

Python provides two straightforward ways to reverse strings. Since strings are sequences, they’re indexable, sliceable, and iterable. These features allow you to use slicing to directly generate a copy of a given string in reverse order. The second option is to use the built-in function reversed() to create an iterator that yields the characters of an input string in reverse order.

Reversing Strings Through Slicing

Slicing is a useful technique that allows you to extract items from a given sequence using different combinations of integer indices known as offsets. When it comes to slicing strings, these offsets define the index of the first character in the slicing, the index of the character that stops the slicing, and a value that defines how many characters you want to jump through in each iteration.

To slice a string, you can use the following syntax:

a_string[start:stop:step]

Your offsets are start, stop, and step. This expression extracts all the characters from start to stop − 1 by step. You’re going to look more deeply at what all this means in just a moment.

All the offsets are optional, and they have the following default values:

Offset Default Value
start 0
stop len(a_string)
step 1

Here, start represents the index of the first character in the slice, while stop holds the index that stops the slicing operation. The third offset, step, allows you to decide how many characters the slicing will jump through on each iteration.

The step offset allows you to fine-tune how you extract desired characters from a string while skipping others:

>>>

>>> letters = "AaBbCcDd"

>>> # Get all characters relying on default offsets
>>> letters[::]
'AaBbCcDd'
>>> letters[:]
'AaBbCcDd'

>>> # Get every other character from 0 to the end
>>> letters[::2]
'ABCD'

>>> # Get every other character from 1 to the end
>>> letters[1::2]
'abcd'

Here, you first slice letters without providing explicit offset values to get a full copy of the original string. To this end, you can also use a slicing that omits the second colon (:). With step equal to 2, the slicing gets every other character from the target string. You can play around with different offsets to get a better sense of how slicing works.

Why are slicing and this third offset relevant to reversing strings in Python? The answer lies in how step works with negative values. If you provide a negative value to step, then the slicing runs backward, meaning from right to left.

For example, if you set step equal to -1, then you can build a slice that retrieves all the characters in reverse order:

>>>

>>> letters = "ABCDEF"

>>> letters[::-1]
'FEDCBA'

>>> letters
'ABCDEF'

This slicing returns all the characters from the right end of the string, where the index is equal to len(letters) - 1, back to the left end of the string, where the index is 0. When you use this trick, you get a copy of the original string in reverse order without affecting the original content of letters.

Another technique to create a reversed copy of an existing string is to use slice(). The signature of this built-in function is the following:

This function takes three arguments, with the same meaning of the offsets in the slicing operator, and returns a slice object representing the set of indices that result from calling range(start, stop, step).

You can use slice() to emulate the slicing [::-1] and reverse your strings quickly. Go ahead and run the following call to slice() inside square brackets:

>>>

>>> letters = "ABCDEF"

>>> letters[slice(None, None, -1)]
'FEDCBA'

Passing None to the first two arguments of slice() tells the function that you want to rely on its internal default behavior, which is the same as a standard slicing with no values for start and stop. In other words, passing None to start and stop means that you want a slice from the left end to the right end of the underlying sequence.

Reversing Strings With .join() and reversed()

The second and arguably the most Pythonic approach to reversing strings is to use reversed() along with str.join(). If you pass a string to reversed(), you get an iterator that yields characters in reverse order:

>>>

>>> greeting = reversed("Hello, World!")

>>> next(greeting)
'!'
>>> next(greeting)
'd'
>>> next(greeting)
'l'

When you call next() with greeting as an argument, you get each character from the right end of the original string.

An important point to note about reversed() is that the resulting iterator yields characters directly from the original string. In other words, it doesn’t create a new reversed string but reads characters backward from the existing one. This behavior is fairly efficient in terms of memory consumption and can be a fundamental win in some contexts and situations, such as iteration.

You can use the iterator that you get from calling reversed() directly as an argument to .join():

>>>

>>> "".join(reversed("Hello, World!"))
'!dlroW ,olleH'

In this single-line expression, you pass the result of calling reversed() directly as an argument to .join(). As a result, you get a reversed copy of the original input string. This combination of reversed() and .join() is an excellent option for reversing strings.

Generating Reversed Strings by Hand

So far, you’ve learned about core Python tools and techniques to reverse strings quickly. Most of the time, they’ll be your way to go. However, you might need to reverse a string by hand at some point in your coding adventure.

In this section, you’ll learn how to reverse strings using explicit loops and recursion. The final technique uses a functional programming approach with the help of Python’s reduce() function.

Reversing Strings in a Loop

The first technique you’ll use to reverse a string involves a for loop and the concatenation operator (+). With two strings as operands, this operator returns a new string that results from joining the original ones. The whole operation is known as concatenation.

Here’s a function that takes a string and reverses it in a loop using concatenation:

>>>

>>> def reversed_string(text):
...     result = ""
...     for char in text:
...         result = char + result
...     return result
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In every iteration, the loop takes a subsequent character, char, from text and concatenates it with the current content of result. Note that result initially holds an empty string (""). The new intermediate string is then reassigned to result. At the end of the loop, result holds a new string as a reversed copy of the original one.

If you prefer using a while loop, then here’s what you can do to build a reversed copy of a given string:

>>>

>>> def reversed_string(text):
...     result = ""
...     index = len(text) - 1
...     while index >= 0:
...         result += text[index]
...         index -= 1
...     return result
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

Here, you first compute the index of the last character in the input string by using len(). The loop iterates from index down to and including 0. In every iteration, you use the augmented assignment operator (+=) to create an intermediate string that concatenates the content of result with the corresponding character from text. Again, the final result is a new string that results from reversing the input string.

Reversing Strings With Recursion

You can also use recursion to reverse strings. Recursion is when a function calls itself in its own body. To prevent infinite recursion, you should provide a base case that produces a result without calling the function again. The second component is the recursive case, which starts the recursive loop and performs most of the computation.

Here’s how you can define a recursive function that returns a reversed copy of a given string:

>>>

>>> def reversed_string(text):
...     if len(text) == 1:
...         return text
...     return reversed_string(text[1:]) + text[:1]
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In this example, you first check for the base case. If the input string has exactly one character, you return the string back to the caller.

The last statement, which is the recursive case, calls reversed_string() itself. The call uses the slice text[1:] of the input string as an argument. This slice contains all the characters in text, except for the first one. The next step is to add the result of the recursive call together with the single-character string text[:1], which contains the first character of text.

A significant issue to note in the example above is that if you pass in a long string as an argument to reversed_string(), then you’ll get a RecursionError:

>>>

>>> very_long_greeting = "Hello, World!" * 1_000

>>> reversed_string(very_long_greeting)
Traceback (most recent call last):
    ...
RecursionError: maximum recursion depth exceeded while calling a Python object

Hitting Python’s default recursion limit is an important issue that you should consider in your code. However, if you really need to use recursion, then you still have the option to set the recursion limit manually.

You can check the recursion limit of your current Python interpreter by calling getrecursionlimit() from sys. By default, this value is usually 1000. You can tweak this limit using setrecursionlimit() from the same module, sys. With these functions, you can configure the Python environment so that your recursive solution can work. Go ahead and give it a try!

Using reduce() to Reverse Strings

If you prefer using a functional programming approach, you can use reduce() from functools to reverse strings. Python’s reduce() takes a folding or reduction function and an iterable as arguments. Then it applies the provided function to the items in the input iterable and returns a single cumulative value.

Here’s how you can take advantage of reduce() to reverse strings:

>>>

>>> from functools import reduce

>>> def reversed_string(text):
...     return reduce(lambda a, b: b + a, text)
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In this example, the lambda function takes two strings and concatenates them in reverse order. The call to reduce() applies the lambda to text in a loop and builds a reversed copy of the original string.

Iterating Through Strings in Reverse

Sometimes you might want to iterate through existing strings in reverse order, a technique typically known as reverse iteration. Depending on your specific needs, you can do reverse iteration on strings by using one of the following options:

  • The reversed() built-in function
  • The slicing operator, [::-1]

Reverse iteration is arguably the most common use case of these tools, so in the following few sections, you’ll learn about how to use them in an iteration context.

The reversed() Built-in Function

The most readable and Pythonic approach to iterate over a string in reverse order is to use reversed(). You already learned about this function a few moments ago when you used it along with .join() to create reversed strings.

However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

Here’s how you can iterate over a string in reverse order with reversed():

>>>

>>> greeting = "Hello, World!"

>>> for char in reversed(greeting):
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> reversed(greeting)
<reversed object at 0x7f17aa89e070>

The for loop in this example is very readable. The name of reversed() clearly expresses its intent and communicates that the function doesn’t produce any side effects on the input data. Since reversed() returns an iterator, the loop is also efficient regarding memory usage.

The Slicing Operator, [::-1]

The second approach to perform reverse iteration over strings is to use the extended slicing syntax you saw before in the a_string[::-1] example. Even though this approach won’t favor memory efficiency and readability, it still provides a quick way to iterate over a reversed copy of an existing string:

>>>

>>> greeting = "Hello, World!"

>>> for char in greeting[::-1]:
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> greeting[::-1]
'!dlroW ,olleH'

In this example, you apply the slicing operator on greeting to create a reversed copy of it. Then you use that new reversed string to feed the loop. In this case, you’re iterating over a new reversed string, so this solution is less memory-efficient than using reversed().

Creating a Custom Reversible String

If you’ve ever tried to reverse a Python list, then you know that lists have a handy method called .reverse() that reverses the underlying list in place. Since strings are immutable in Python, they don’t provide a similar method.

However, you can still create a custom string subclass with a .reverse() method that mimics list.reverse(). Here’s how you can do that:

>>>

>>> from collections import UserString

>>> class ReversibleString(UserString):
...     def reverse(self):
...         self.data = self.data[::-1]
...

ReversibleString inherits from UserString, which is a class from the collections module. UserString is a wrapper around the str built-in data type. It was specially designed for creating subclasses of str. UserString is handy when you need to create custom string-like classes with additional functionalities.

UserString provides the same functionality as a regular string. It also adds a public attribute called .data that holds and gives you access to the wrapped string object.

Inside ReversibleString, you create .reverse(). This method reverses the wrapped string in .data and reassigns the result back to .data. From the outside, calling .reverse() works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.

Here’s how ReversibleString works in practice:

>>>

>>> text = ReversibleString("Hello, World!")
>>> text
'Hello, World!'

>>> # Reverse the string in place
>>> text.reverse()
>>> text
'!dlroW ,olleH'

When you call .reverse() on text, the method acts as if you’re doing an in-place mutation of the underlying string. However, you’re actually creating a new string and assigning it back to the wrapped string. Note that text now holds the original string in reverse order.

Since UserString provides the same functionality as its superclass str, you can use reversed() out of the box to perform reverse iteration:

>>>

>>> text = ReversibleString("Hello, World!")

>>> # Support reverse iteration out of the box
>>> for char in reversed(text):
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> text
"Hello, World!"

Here, you call reversed() with text as an argument to feed a for loop. This call works as expected and returns the corresponding iterator because UserString inherits the required behavior from str. Note that calling reversed() doesn’t affect the original string.

Sorting Python Strings in Reverse Order

The last topic you’ll learn about is how to sort the characters of a string in reverse order. This can be handy when you’re working with strings in no particular order and you need to sort them in reverse alphabetical order.

To approach this problem, you can use sorted(). This built-in function returns a list containing all the items of the input iterable in order. Besides the input iterable, sorted() also accepts a reverse keyword argument. You can set this argument to True if you want the input iterable to be sorted in descending order:

>>>

>>> vowels = "eauoi"

>>> # Sort in ascending order
>>> sorted(vowels)
['a', 'e', 'i', 'o', 'u']

>>> # Sort in descending order
>>> sorted(vowels, reverse=True)
['u', 'o', 'i', 'e', 'a']

When you call sorted() with a string as an argument and reverse set to True, you get a list containing the characters of the input string in reverse or descending order. Since sorted() returns a list object, you need a way to turn that list back into a string. Again, you can use .join() just like you did in earlier sections:

>>>

>>> vowels = "eauoi"

>>> "".join(sorted(vowels, reverse=True))
'uoiea'

In this code snippet, you call .join() on an empty string, which plays the role of a separator. The argument to .join() is the result of calling sorted() with vowels as an argument and reverse set to True.

You can also take advantage of sorted() to iterate through a string in sorted and reversed order:

>>>

>>> for vowel in sorted(vowels, reverse=True):
...     print(vowel)
...
...
u
o
i
e
a

The reverse argument to sorted() allows you to sort iterables, including strings, in descending order. So, if you ever need a string’s characters sorted in reverse alphabetical order, then sorted() is for you.

Conclusion

Reversing and working with strings in reverse order can be a common task in programming. Python provides a set of tools and techniques that can help you perform string reversal quickly and efficiently. In this tutorial, you learned about those tools and techniques and how to take advantage of them in your string processing challenges.

In this tutorial, you learned how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Use iteration and recursion to create reversed strings by hand
  • Loop over your strings in reverse order
  • Sort your strings in descending order using sorted()

Even though this topic might not have many exciting use cases by itself, understanding how to reverse strings can be useful in coding interviews for entry-level positions. You’ll also find that mastering the different ways to reverse a string can help you really conceptualize the immutability of strings in Python, which is a notable feature of the language.

In this tutorial, we will learn how to reverse words of a string given by the user in python. Before getting on to the actual code, let us learn some string methods.

split() method

As the name suggests, the split() method basically splits the string into a list. You can condition it based on separator and maximum splits you want it to do. Default separator is a white space and default maximum split value is -1 (i.e. all the times).  You can split at ‘,’, ‘:’, ‘#’, etc.

Syntax:

string.split(separator, max_split)

Example:

string = "codespeedy is the best"

print(string.split())

Output:

['codespeedy', 'is', 'the', 'best']

reverse() method

There are various ways to reverse a string like reversed() function, using [::-1] to print in the reversed order or using the reverse() method. Each one has it’s own usage, advantages and disadvantages. In this tutorial, we have used reverse() method which will directly reverse and modify the original list.

Syntax:

list.reverse()

Example:

list = ['1', '2', '3', '4']

print(list.reverse())

Output:

['4','3','2','1']

join() method

join() method simply concatenate iterable-object like the elements of list, tuple, string, etc. This function returns a string with all the elements joined by string separator.

Syntax:

string.join(element)

Example:

list = ['1', '2', '3', '4']

separator = '-'

print(separator.join(list))

Output:

1-2-3-4

Reversing words of a string in Python

Problem statement: Write a python program to reverse words of a given string.

Steps/Algorithm:

  1. Take the string input from user.
  2. Split the string using split() function.
  3. Use the reverse() method to reverse all the words that have been split from the string.
  4. Finally, join and print them using the join() function.

Code/Program:

x = input("Enter any string: ")
#take input from user

a = x.split()
#use split method to split at whitespaces

a.reverse()
#reverse all the elements of the string 

print(' '.join(a))
#concatenate them into a string

Run the program online
Output:

Enter any string: codespeedy is the best
best the is codespeedy

NOTE: There may be other possible ways to solve this problem.

Also read:

  • How to reverse the elements in a list in Python by its index

In this python tutorial, you will learn about the python program to reverse a string.

There are 8 methods to reverse the string in Python, which are shown below.

  • Using the slicing method
  • Using the reversed() function
  • Using For loop
  • Using the Recursion
  • Using join() and list comprehension method
  • Using the reduce() function
  • Using the stack
  • Using the list comprehension
  • Using the while loop

Let us all 8 methods to reverse a string in Python using examples. And we will start with the first method of using slicing.

Method-1: Python program to reverse a string using the slicing method

This method uses the slicing of Python strings to reverse the string by starting from the last character and returning every character to the first one with a step of -1.

# Function to reverse a string
def reverse_string(string):
    # Returns the reversed string by slicing from the end to the beginning
    return string[::-1]

# Testing the function with the input string "United Kingdom"
print("Reverse of the string is : ", reverse_string("United Kingdom"))

The above code defines a function called reverse_string which takes a string as an argument and returns the reverse of the input string using string slicing. The function is then called and the reverse of the string “United Kingdom” is printed to the console.

Python program to reverse a string
Python reverse string Using the slicing method

Read: How to Check if a String contains a Substring in Python

Method-2: Python program to reverse a string using the reversed() function

The reversed() function returns a reverse iterator, so we can convert it into a string using the join() method. This method is easy to use and more efficient than some other methods.

# Function to reverse a string
def reverse_string(string):
    # Return the reversed string using the reversed() function and join() method
    return "".join(reversed(string))

# Print the reversed string
print("Reverse of the string is : ", reverse_string("USA"))

The above code defines a function reverse_string which takes a string as an argument and returns the reversed version of the string.

The function uses the reversed function and the join method to reverse the string. The code then calls the reverse_string function with the argument “USA” and prints the returned value, which is the reverse of the string “USA”.

Output: Reverse of the string is :  ASU

Read: Python string formatting

Method-3: Python program to reverse a string using For loop

In this method, we use a for loop to iterate over the characters in the string and build a new string by adding each character to the beginning of an empty string.

# Function to reverse a string
def reverse_string(string):
    # Initialize an empty string
    result = ""
    # Loop through each character in the string and add it to the beginning of the result string
    for char in string:
        result = char + result
    # Return the reversed string
    return result

# Call the function with a string "Canada" as an argument
print("Reverse of the string is : ", reverse_string("Canada"))

The above code defines a function reverse_string which takes a string as input and returns the reverse of that string by concatenating each character from the end to the start of the string into a new result string.

  • The function is then called with the string “Canada” and the resulting reverse string is printed.
Outptut: Reverse of the string is :  adanaC

Read: Python compare strings

Method-4: Python program to reverse a string using the Recursion

This method uses recursion to reverse the string. The base case of the recursion is an empty string, and for each recursive call, the first character is added to the end of the reverse of the rest of the string.

# Function to reverse a string using recursion
def reverse_string(string):
    # Base case: If the length of the string is 0, return the string
    if len(string) == 0:
        return string
    else:
        # Recursive step: Return the last character of the string + the reverse of the rest of the string
        return reverse_string(string[1:]) + string[0]

# Testing the reverse_string function with the input "New York"
print("Reverse of the string is : ", reverse_string("New York"))
Output: Reverse of the string is :  kroY weN

Read: Python find number in String

Method-5: Python program to reverse a string using join() and list comprehension method

This method uses the join() method to concatenate the characters in the string in reverse order, generated through a generator expression that iterates over the string in reverse order.

# Function to reverse a string using list comprehension
def reverse_string(string):
    return "".join(string[i] for i in range(len(string)-1, -1, -1))

# Reverse the string "Brazil" and print the result
print("Reverse of the string is : ", reverse_string("Brazil"))

The above code defines a function reverse_string that takes a string as an argument. The function returns a reversed version of the string using the built-in join method.

  • The join method concatenates the elements of the string, which are obtained using the list comprehension that iterates through the string in reverse order (i.e., from the last index to the first index).
Output: Reverse of the string is :  lizarB

Read: Find first number in string in Python

Method-6: Python program to reverse a string using the reduce() function

This method uses the reduce() function from the functools module to apply a binary function to the elements of the string in reverse order, creating a single cumulative value.

# Function to reverse a string using reduce method
from functools import reduce

def reverse_string(string):
    # Using reduce to concatenate the characters in the string in reverse order
    return reduce(lambda x, y: y + x, string)

# Testing the reverse_string function
print("Reverse of the string is : ", reverse_string("Australia"))

The above code is a python script that reverses a string using the reduce() method from the functools library. The script defines a function called reverse_string which takes a string as an argument.

  • The function returns the reversed string by using the reduce() method with a lambda function as an argument.
Output: Reverse of the string is :  ailartsuA

Read: Remove non-ASCII characters Python

Method-7: Python program to reverse a string using the stack

This method uses a stack data structure to reverse the string. The stack is created by pushing each character in the string onto it and then popping the characters off the stack to build the reversed string.

# Function to reverse a string using a stack
def reverse_string(string):
    # Create a stack of characters from the input string
    stack = [char for char in string]
    # Initialize an empty string to store the result
    result = ""
    # Pop characters from the stack and add them to the result until the stack is empty
    while stack:
        result += stack.pop()
    # Return the reversed string
    return result

# Test the function by passing a sample string
print("Reverse of the string is : ", reverse_string("Washington"))

The above code defines a function reverse_string that takes in a string as an argument and returns its reverse.

  • The function uses a stack data structure to store the characters of the string and then pops the elements from the stack to get the reverse string.
  • Finally, the reversed string is returned and printed.
Output: Reverse of the string is :  notgnihsaW

Read: How to trim a string in Python

Method-8: Python program to reverse a string using the while loop

A while loop is used to iterate over the indices of the string in reverse order (from the last character to the first character).

# Function to reverse a string
def reverse_string(string):
    # Initializing an empty string to store the reverse
    result = ""
    # Finding the length of the string
    length = len(string)
    # Iterating through the string in reverse order
    while length > 0:
        # Decreasing the length by 1
        length -= 1
        # Adding the character to the result string
        result += string[length]
    # Returning the reverse string
    return result

# Printing the reverse of the string
print("Reverse of the string is : ", reverse_string("Amazon"))

The above code defines a function reverse_string which takes a string as an argument and returns its reverse by concatenating the characters in reverse order.

  • The reverse string is calculated using a loop that starts from the end of the input string and goes till the start.
  • For each iteration, the character at the current index is added to the result string.
Output: Reverse of the string is :  nozamA

You may also like to read the following Python tutorials.

  • How to concatenate strings in python
  • Python remove substring from a String
  • Python string uppercase() method with examples

In this Python tutorial, we have learned about the Python program to reverse a string using the following methods:

  • Using the slicing method
  • Using the reversed() function
  • Using For loop
  • Using the Recursion
  • Using join() and list comprehension method
  • Using the reduce() function
  • Using the stack
  • Using the list comprehension
  • Using the while loop

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Понравилась статья? Поделить с друзьями:
  • Reverse the word order
  • Reverse the text in word
  • Reverse the text in excel
  • Reverse the string word by word in java
  • Reverse print in word