-2

I want to reverse a string using slicing and initially I tried

string = "abcdef" 
print(string[len(string) - 1: 0: -1])

However this only prints up to the index 1

fedcb

So, I decided to change the slicing by changing the ending index of the slicing to -1

string = "abcdef" 
print(string[len(string) - 1: -1: -1])

I'm assuming this will print up to index 0. But this did not print any characters of the string upon running. My question is why doesn't this work?

4 Answers4

1

from the docs slice:

 class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None.

you can use the [::-1] index to do that

>>> s = 'hello'
>>> s[::-1]
'olleh'

with a negative step, the index will go from -1 to ~(len(s)-1), and by that I mean that the string will go from index -1 to 0 reversed

XxJames07-
  • 1,833
  • 1
  • 4
  • 17
1

for your question,

string = "abcdef" 
print(string[len(string) - 1: -1: -1])

returns an empty string since it's taking the second argument as the stopping point : which is exactly the last character that's why it's empty ,

you can test it by running :

    string = "abcdef" 
    print(string[len(string) - 1: -2: -1])

it only returns the character 'f' xhich is the last character .

Now for what you're trying to achieve : you can either use :

string = "abcdef" 
print(string[-1: -len(string)-1: -1])
##or 
print(string[::-1])
Ran A
  • 746
  • 3
  • 7
  • 19
0

This is what you're looking for:

string = "abcdef"
print(string[::-1])
htaccess
  • 2,800
  • 26
  • 31
Hannon qaoud
  • 785
  • 2
  • 21
0

This question seems to be a Tricky one

Below is a table describing the structure for a slice[] operator

-6 0 1 2 3 4 5 PositiveIndex
A p p l e
-6 -5 -4 -3 -2 -1 5 NegativeIndex

slice[] operator takes in start, stop and step.
We know that stop is excluded, so if we want to extreme values to be included in the result we can leave it empty or put a value greater than highest index

>>>a='Apple'
>>>a[::]
'Apple'
>>>a[::-1]
'elppA'
>>>a[-5:-1:1]
'Appl'
>>>a[-5:5:1]
'Apple'
>>>a[4:0:-1]
'elpp'
>>>a[4:-6:-1]
'elppA'