python Inversion of of Reverse String Six Methods Detailed

  • 2021-10-24 23:12:45
  • OfStack

For a given string, output in reverse order, this task is a very simple operation for python. After all, powerful list and string processing functions are enough to cope with these problems. Today, we summarize several commonly used methods for string output in reverse order in python under 1

Method 1: Reverse the string directly using the string slicing function


>>> def strReverse(strDemo):
	return strDemo[::-1]
>>> print(strReverse('ofstack.com'))
ten.15bj

Results:

ten.15bj

Method 2: Traversing the construction list method

Loop through a string, construct a list, add elements from back to front, and finally turn the list into a string


>>> def strReverse(strDemo):
	strList=[]
	for i in range(len(strDemo)-1, -1, -1):
		strList.append(strDemo[i])
	return ''.join(strList)

>>> print(strReverse('ofstack.com'))
ten.15bj

Results:

ten.15bj

Method 3: Use the reverse function

Converting a string to a list uses the reverse function


>>> def strReverse(strDemo): 
	strList = list(strDemo) 
	strList.reverse() 
	return ''.join(strList)

>>> print(strReverse('ofstack.com'))
ten.15bj

Results:

ten.15bj

Method 4: extendleft with the help of collections module method


>>> import collections
>>> def strReverse(strDemo): 
	deque1=collections.deque(strDemo) 
	deque2=collections.deque() 
	for tmpChar in deque1: 
		deque2.extendleft(tmpChar) 
	return ''.join(deque2)

>>> print(strReverse('ofstack.com'))
ten.15bj

Results:

ten.15bj

Method 5: Recursive implementation


>>> def strReverse(strDemo): 
	if len(strDemo)<=1: 
		return strDemo 
	return strDemo[-1]+strReverse(strDemo[:-1])

>>> print(strReverse('ofstack.com'))
ten.15bj

Results:

ten.15bj

Method 6: With the help of basic Swap operation, exchange symmetrical characters with the middle as the reference


>>> def strReverse(strDemo): 
	strList=list(strDemo) 
	if len(strList)==0 or len(strList)==1: 
		return strList 
	i=0 
	length=len(strList) 
	while i < length/2: 
		strList[i], strList[length-i-1]=strList[length-i-1], strList[i] 
		i+=1
	return ''.join(strList)

>>> print(strReverse('ofstack.com'))
ten.15bj

Results:

ten.15bj

Here are the 6 methods of python inversion (reverse order) strings explained in this article. For more information about python inversion (reverse order) strings, please see the related links below


Related articles: