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:

程序:

  1. First create an empty stack

    首先创建一个空栈

  2. Push each character one by one in stack

    将每个字符一一推送

  3. 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 sys

def push(element, size, stack):
    '''
    this function is used to push the elements
    in the stack and it will return Error! message
    if the stack is full and terminate the program.
    '''
    global top
    if top >= size - 1:
        print('Stack Overflow')
        sys.exit()
    else:
        top += 1
        stack[top] = element

def pop():
    '''
    this function is used to pop elements from
    the stack and it will return Error! message
    if the stack is empty and terminate the program.
    '''
    global top
    if top < 0:
        print('Stack Underflow')
        sys.exit()
    else:
        element = stack[top]
        print('%s' % element, end='')
        top -= 1

def reverse_by_sort(string):
    '''
    This function is used to reverse any string
    by reversed() method.
    '''

    string = list(string)
    rev_str = ''
    
    for i in reversed(string):
        rev_str += i

    return rev_str

if __name__=='__main__':

    size = 11
    stack = [0]*size
    string = 'Includehelp'
    top = -1

    # Pushing value in the stack
    push('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 them
    print('Reversed String = ',end='')
    for i in stack:
        pop()

    print('\n\nUsing sort()')
    print('Reversed string = %s' % reverse_by_sort(string))

Output

输出量

Original String = Includehelp

Using Stack
Reversed String = plehedulcnI

Using sort()
Reversed string = plehedulcnI


翻译自: https://www.includehelp.com/python/reverse-a-string-using-stack-and-reversed-method.aspx

python字符串反转方法

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值