Home >Backend Development >Python Tutorial >How to reverse the specified string in python
Python's method of reversing the specified string: 1. Directly use the string slicing function to reverse the string; 2. Traverse the construction list method; 3. Use the reverse function to implement; 4. Use the collections module method extendleft; 5. Use recursion.
Python method to reverse the specified string:
Method 1: Use string slicing directly Function to reverse string
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): return strDemo[::-1] print(strReverse('pythontab.com'))
Result:
moc.batnohtyp
Method 2: Traversal construction list method
Loop through the string, construct a list, add elements from back to front, and finally turn the list into a string
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): strList=[] for i in range(len(strDemo)-1, -1, -1): strList.append(strDemo[i]) return ''.join(strList) print(strReverse('pythontab.com'))
Result:
moc.batnohtyp
Method 3: Use the reverse function
Convert the string to a list using the reverse function
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): strList = list(strDemo) strList.reverse() return ''.join(strList) print(strReverse('pythontab.com'))
Result:
moc.batnohtyp
Method 4: Use the collections module method extendleft
#!usr/bin/env python # encoding:utf-8 import collections def strReverse(strDemo): deque1=collections.deque(strDemo) deque2=collections.deque() for tmpChar in deque1: deque2.extendleft(tmpChar) return ''.join(deque2) print(strReverse('pythontab.com'))
Result:
moc.batnohtyp
Method 5: Recursive implementation
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): if len(strDemo)<=1: return strDemo return strDemo[-1]+strReverse(strDemo[:-1]) print(strReverse('pythontab.com'))
Result:
moc.batnohtyp
Method 6: Use the basic Swap operation to exchange symmetrically positioned characters based on the middle
#!usr/bin/env python #encoding:utf-8 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: s trList[i], strList[length-i-1]=strList[length-i-1], strList[i] i+=1 return ''.join(strList) print(strReverse('pythontab.com'))
Result:
moc.batnohtyp
##Related free learning recommendations: python video tutorial
The above is the detailed content of How to reverse the specified string in python. For more information, please follow other related articles on the PHP Chinese website!