In this shot, we will look at how to reverse a string in Python. An example of what this entails is given below.
"this is an example"
"example an is this"
We will use the in-built methods
reversed() to solve this problem.
split(): This method splits the given string into a list.
reversed(): This function returns the list in reversed order.
join(): This method joins the given list, with the provided string in-between them.
split()on the basis of the space
#original string s = "this is an example" print("Original string -> " + s) #split the string where space is present word_list = s.split(" ") print("List of words after splitting -> " + str(word_list)) #reverse the list reversed_list = list(reversed(word_list)) print("Reversed list of words -> " + str(reversed_list)) #join reversed list reversed_str = " ".join(reversed_list) print("Reversed String -> " + reversed_str)
In the following code snippet:
swhere the character
spaceis present using the
word_listwith the function
reversed(), which returns a list iterator, and convert it into the list.
space, using the
View all Courses