Reverse string: string[::-1] works, but string[0::-1] and others don't

前端 未结 2 1659
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 00:25

I am somewhat of a python/programming newbie, and I have just been playing around with string slicing. So the simple string reverse method of string[::-1] works jus

2条回答
  •  耶瑟儿~
    2021-01-30 00:51

    In all of your cases which aren't working, you're starting at the beginning and then moving backwards. There is no further backwards than the beginning, so you don't get any more characters.

    This would be the solution:

    >>> string[len(string)::-1]
    'ydood ydwoH'
    

    The slice notation is start, end, step. Where step is negative, start should be greater than end to get anything. Where it's left blank ([::-1]), that nuance is followed automatically

    In the case where you only got 'H', it can be confusing why there was anything. But think of the explanation written out:

    Beginning with the character at start, increment by step until (but not including) end

    Now it becomes clear that because you start with 0, the 0 character is included

提交回复
热议问题