In Python, strings are ordered sequences of character data.
There is no built-in method to reverse a string. However, strings can be reversed in several different ways.
Three methods to reverse a string are explained below:
Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0.
To reverse a string using slicing, write:
stringname[stringlength::-1] # method 1
Or write without specifying the length of the string:
stringname[::-1] # method2
The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).
s="Python" # initial stringstringlength=len(s) # calculate length of the listslicedString=s[stringlength::-1] # slicingprint (slicedString) # print the reversed string
To start, let’s create a new array called reversedString[]
.
We can then loop over the list with iterating variable index
initialized with the length of the list.
We then simply keep iterating until the index is less than zero.
s = "Python" # initial stringreversedString=[]index = len(s) # calculate length of string and save in indexwhile index > 0:reversedString += s[ index - 1 ] # save the value of str[index-1] in reverseStringindex = index - 1 # decrement indexprint(reversedString) # reversed string
This is a powerful technique that takes advantage of Python’s iterator protocol. This technique reverses a string using reverse iteration with the reversed()
built-in function to cycle through the elements in the string in reverse order and then use .join()
method to merge all of the characters resulting from the reversed iteration into a new string.
The general syntax is
s="Python"
reversedstring=''.join(reversed(s))
The following Python code demonstrates the concept.
s = 'Python' #initial stringreversed=''.join(reversed(s)) # .join() method merges all of the characters resulting from the reversed iteration into a new stringprint(reversed) #print the reversed string