python字符串反转方法_Python程序使用堆栈和反转方法反转字符串
python字符串反轉方法
Given a string and we have to reverse it by using stack and by using reversed method in python.
給定一個字符串,我們必須使用堆棧和python中的反轉方法來反轉它。
1)通過使用堆棧反轉字符串 (1) Reverse a string by using stack)
Procedure:
程序:
First create an empty stack
首先創建一個空棧
Push each character one by one in stack
將每個字符一一推送
Pop each character one by one and put them back to the string
逐個彈出每個字符,然后將其放回字符串
2)使用reversed()方法反轉串 (2) Reverse a strung using reversed() method)
In this method, we will use reversed() method and iterate over the reversed iterator to get the reversed string.
在此方法中,我們將使用reversed()方法并在反向迭代器上進行迭代以獲取反向字符串。
Python代碼反轉字符串 (Python code to reverse a string )
import sysdef push(element, size, stack):'''this function is used to push the elementsin the stack and it will return Error! messageif the stack is full and terminate the program.'''global topif top >= size - 1:print('Stack Overflow')sys.exit()else:top += 1stack[top] = elementdef pop():'''this function is used to pop elements fromthe stack and it will return Error! messageif the stack is empty and terminate the program.'''global topif top < 0:print('Stack Underflow')sys.exit()else:element = stack[top]print('%s' % element, end='')top -= 1def reverse_by_sort(string):'''This function is used to reverse any stringby reversed() method.'''string = list(string)rev_str = ''for i in reversed(string):rev_str += ireturn rev_strif __name__=='__main__':size = 11stack = [0]*sizestring = 'Includehelp'top = -1# Pushing value in the stackpush('I', 11, stack)push('n', 11, stack)push('c', 11, stack)push('l', 11, stack)push('u', 11, stack)push('d', 11, stack)push('e', 11, stack)push('h', 11, stack)push('e', 11, stack)push('l', 11, stack)push('p', 11, stack)print('Original String = %s' % string)print('\nUsing Stack')# Popping values from stack and printing themprint('Reversed String = ',end='')for i in stack:pop()print('\n\nUsing sort()')print('Reversed string = %s' % reverse_by_sort(string))Output
輸出量
Original String = IncludehelpUsing Stack Reversed String = plehedulcnIUsing sort() Reversed string = plehedulcnI翻譯自: https://www.includehelp.com/python/reverse-a-string-using-stack-and-reversed-method.aspx
python字符串反轉方法
總結
以上是生活随笔為你收集整理的python字符串反转方法_Python程序使用堆栈和反转方法反转字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c ++产生不同的随机数_C ++程序生
- 下一篇: java 方法 示例_Java集合asL