In this shot, we will look at how to reverse a string in Python. An example of what this entails is given below.
Input: "this is an example"
Output: "example an is this"
We will use the in-built methods split()
, join()
, and 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 " "
character.split()
method.join()
method.#original strings = "this is an example"print("Original string -> " + s)#split the string where space is presentword_list = s.split(" ")print("List of words after splitting -> " + str(word_list))#reverse the listreversed_list = list(reversed(word_list))print("Reversed list of words -> " + str(reversed_list))#join reversed listreversed_str = " ".join(reversed_list)print("Reversed String -> " + reversed_str)
In the following code snippet:
s
where the character space
is present using the split(" ")
method.word_list
with the function reversed()
, which returns a list iterator, and convert it into the list.space
, using the join()
method.