Reverse a word in python | Letters in word and Sentences

It a very easy to Reverse words in a string python, you have to first Separate each word, then Reverse the word separated list, and in the last join each word with space.

For all this step you needed a split(), join() , reversed() function and list data structure.

Algorithm of reverse words in a sentence

  1. Initialize the string.
  2. Split the string on space and store the resultant list.
  3. Reverse the list words.
  4. Convert the result to the list.
  5. Join the words using the join function and print them.

Example of Reverse words in a given String in Python

# initializing the string
string = "A Python Programming language"

# splitting the string on space
words_list = string.split()

# reversing the words List using reversed() function
rev_words_list = list(reversed(words_list))

# joining the words and printing
print(" ".join(rev_words_list))

Output: language Programming Python A

Q: How to Python reverse letters in a word?

Answer:

Reverse letters in words and sentence both:

In example taking user input, you can use any sentences.

sentence = input("Input a word to reverse: ")

for char in range(len(sentence) - 1, -1, -1):
    print(sentence[char], end="")
print("\n")

Output:

Reverse only letters in word

Sentence = "EyeHunts for student"

rev_letters = ' '.join(word[::-1] for word in Sentence.split(" "))
print(rev_letters)

Q: Write a python program that accepts a word from the user and reverse it.

Answer: Example of that accepts a word from the user and reverse it.

word = input("Input a word to reverse: ")

for char in range(len(word) - 1, -1, -1):
    print(word[char], end="")
print("\n")

Q: How to reverse a string in python using for loop?

Answer:

def reverse(text):
    a = ""
    for i in range(1, len(text) + 1):
        a += text[len(text) - i]
    return a

print(reverse("Hello World!")) # prints: !dlroW olleH

Read More: Python reverse string | Using loop, recursion, stack, slice, reversed

Do comment if you have any doubts and suggestion on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.