Reverse String through indices. | Python Language Forum
H
Heena Goyal Posted on 26/07/2023
mystr="Akash is a good boy"
print(len(mystr))
print(mystr[ : :-1])
print(mystr[0:19:-1])
print(mystr[0:19])


Output:

19
yob doog a si hsakA

Akash is a good boy



So, here if we leave start and stop blank, it will take the default values or the actual length of the string. That means it does not matter if we define start and stop or not, we will get the same output i.e. the string.

Now, we leave start and stop blank and mention step as -1, it reverses our string.
So, when we use -1 as step with start and stop mentioned, it gives us blank as an output. why blank if mentioning the start and stop default values is one and the same thing.

Y
Yogesh Chawla Replied on 26/07/2023

mystr="Akash is a good boy"
print(len(mystr)) # calculates the length of a string
#There is no built-in function to reverse a String in Python. The fastest (and easiest) way is to use a slice that steps backwards, -1.
print(mystr[ : :-1])

start = 0
stop = 19

# slicing from index start to index stop-1
print(mystr[start:stop])

# slicing from index start to the end
print(mystr[start:])

# slicing from the beginning to index stop - 1
print(mystr[:stop])

# slicing from the index start to index stop, by skipping step
step = 1 #it will not step anything
print(mystr[start:stop:step])

step = 2 #it step to secod letter
print(mystr[start:stop:step])

step = -1 #it step to secod letter
print(mystr[stop:start:step]) #The earlier one was not working because you mentioned -1 as step so you have to start from higher number and step
with value -1 then you will get the output

step = -2 #it step to second letter
print(mystr[stop:start:step])

# slicing from 1st to last in steps of 1 in reverse order
print(mystr[::-1])

#Here you are passing step value as -1 meaning
print(mystr[19:0:-1])
print(mystr[19:0:-1])
print(mystr[0:19])