Reverse a string in Python

前端 未结 28 2578
南旧
南旧 2020-11-21 04:41

There is no built in reverse function for Python\'s str object. What is the best way of implementing this method?

If supplying a very conci

28条回答
  •  被撕碎了的回忆
    2020-11-21 05:10

    This class uses python magic functions to reverse a string:

    class Reverse(object):
        """ Builds a reverse method using magic methods """
    
        def __init__(self, data):
            self.data = data
            self.index = len(data)
    
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.index == 0:
                raise StopIteration
    
            self.index = self.index - 1
            return self.data[self.index]
    
    
    REV_INSTANCE = Reverse('hello world')
    
    iter(REV_INSTANCE)
    
    rev_str = ''
    for char in REV_INSTANCE:
        rev_str += char
    
    print(rev_str)  
    

    Output

    dlrow olleh
    

    Reference

提交回复
热议问题