Reverse words in a string python without using function

Learn about Reversing Words in a String Python.

Overview

We are given a string as an input in Python, and our task is to reverse words present in the string. We will use different string functions in Python to complete the program.

Scope

  • In this article, we will learn how to reverse the words of a string given as input in Python.
  • We will study how to implement Python built-in string functions like split(), reversed(), and join() in our program to reverse words in a string.

How To Reverse Words In A String Python ?

In Python, a string is created by putting a stream of characters inside single quotes, double quotes, or triple quotes. Reverse words in a string mean that we have to reverse the position of all words in the given string.

Examples

Let us look at some examples :

Input: Hello World
Output: World Hello

Input: I love Programming
Output: Programming love I

Method - 1 : Reverse The Individual Words And Then Reverse The Whole String

The intuition of this approach is to first reverse every word present in the string individually,

For Example :
I like coding becomes, I ekil gnidoc. Now, we have to reverse the whole string to get the desired result which in the case of this example will be coding like I.

Let us now see the implementation of this approach to reverse words in a string in Python :

def reverseWord(s, start, end):
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list(s)
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index(' ', start)
        # Call reverseWord for each word
        reverseWord(s, start, end - 1)
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord(s, start, len(s) - 1)
        break

# reverse the entire list
s.reverse()

# convert the character list back to string
s = "".join(s)

print(s)

Output :

Complexity analysis

Since we are traversing the whole string once to reverse the words in a string, the Time Complexity is O(n)O(n), where nn is the size of the string.

While an auxiliary space is required to reverse words in a string, the Space Complexity is O(n)O(n), where nn is the size of the string.

Method - 2 : By Splitting The String Using The split() Function In Python

The above-discussed method does not handle the case when the string starts with a space. Therefore, we will now discuss an approach that uses Python's in-built split() function. The algorithm to implement this method is as follows :

  1. Define a function that will take a string as input.
  2. Split the input string on space using the split() function and store the result in the form of a list.
  3. Reverse the created list using the reversed() function and add them to a new string using the join() string function in Python.
  4. Return the new string

Let us now see the implementation of this approach to reverse words in a string in Python :

def reverseWords(s):
    words = s.split(' ')
    reverse_str = ' '.join(reversed(words))
    return reverse_str

s1 = "I love Programming"
print (reverseWords(s1))

Output :

The built-in reversed() function in Python returns an iterator object rather than an entire list.

Complexity analysis

Since we are traversing the whole string to split it in space, the Time Complexity is O(n)O(n) , where nn is the size of the string.

While an auxiliary space is required to store the string in a reverse manner, the Space Complexity is O(n)O(n) , where nn is the size of the string.

Now we will discuss an optimal approach to reverse words in a string Python, the intuition of this approach is to swap the words of the string from the beginning and end, using a two-pointer approach, to reverse the string in constant space.

The algorithm is demonstrated as follows :

  1. Convert the string into an array of strings, by splitting it on space.
  2. Initialize the two pointers left and right to 0 and len(string) – 1 respectively.
  3. While the left pointer does not exceed the right pointer, swap the elements at the left and right pointer, move the left pointer forward and the right pointer backward by 1 step.
  4. Finally, return the final reversed string.

Let us now see the implementation of this approach to reverse words in a string in Python :

def reverseWords(s):

    # splitting the string
    s = s.split(" ")

    # initializing 2 pointers
    left = 0
    right = len(s) - 1

    # traversing till left does not exceed right pointer
    while left <= right:
    	# swap elements
        s[left], s[right] = s[right], s[left]

        # increment left and decrement right
        left += 1
        right -= 1

    s = " ".join(s)
    return s

s = 'I love Programming'
print(reverseWords(s))

Output :

Complexity analysis

Since we are traversing the whole string to split it in space, the Time Complexity is O(n)O(n), where nn is the size of the string.

While an auxiliary space is required to store the string in a reverse manner, the Space Complexity is O(1)O(1).

Learn More

To study in-depth about the split function in Python please refer here.

To learn more about the join function in Python check this article.

Conclusion

  • In this article, we have used Python built-in string functions like split(), reversed(), and join() in our program to reverse words in a string.
  • The Optimal Approach for the program has the Time Complexity O(n )O(n) and Space Complexity O(1)O(1) .
  • You can try solving this problem with the help of Regular Expressions also.

How do you reverse a string in Python without functions?

Reverse string in Python using an extended slice 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 the end and stop at the start, hence reversing a string.

How do you reverse a word in Python without function?

for i in my_string: Now, since we are iterating, we will be using the iterating variable. We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time. By end of the for loop, str will contain the given string in reverse order.

How do you reverse a word in a string 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..

How can I reverse a string without any inbuilt function?

Solution 1: Using charAt() Method String class charAt() method which takes the index and returns the character at the given position. In the above program, We are running a for loop from index 0 to its length. charAt(index) is invoked for each index and adding it to the new string revString.