Use the split() method to split a string into a list of words.
Reverse each word from a list
finally, use the join() function to convert a list into a string
Solution:
Split the given string into a list of words using the split() method
Use a list comprehension to create a new list by reversing each word from a list.
Use the join() function to convert the new list into a string
Display the resultant string
# Exercise to reverse each word of a string
def reverse_words(Sentence):
# Split string on whitespace
words = Sentence.split(" ")
# iterate list and reverse each word using ::-1
new_word_list = [word[::-1] for word in words]
# Joining the new list of words
res_str = " ".join(new_word_list)
return res_str
# Given String
str1 = "My Name is Jessa"
print(reverse_words(str1))
Hint:
split()
method to split a string into a list of words.join()
function to convert a list into a stringSolution:
split()
methodjoin()
function to convert the new list into a string