日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python字符串反转方法_Python程序使用堆栈和反转方法反转字符串

發布時間:2025/3/11 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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程序使用堆栈和反转方法反转字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。