How do you reverse a Python string without omitting the start and end slice arguments?
word = "hello"
reversed_word = word[::-1]
I understand that this works, but how would I get the result by specifying the start and end indexes?
word = "hello"
reversed_word = word[?:?:-1]
It's hard to explain to students why word[::-1]
reverses a string. It's better if I can give them logical reasoning rather than "it's the pythonic way".
The way I explain word[::1]
is as follows: "You have not specified the start so it just starts from the start. You have not specified the end so it just goes until the end. Now the step is 1 so it just goes from the start to the end 1 character by 1." Now when my students see word[::-1]
they are going to think "We have not specified the start or the end so it will go through the string -1 characters at a time?"
Just create a new empty str variable and concatenate it. str5 = 'peter piper picked a peck of pickled peppers. ' b = str5. split() rev_str5 = "" for i in b: rev_str5 = rev_str5 + ' ' + i[::-1] print(rev_str5.
Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).
To reverse a string using slicing, omit the start and stop arguments and use a negative step increment of -1 . The negative step increment of -1 means that the slicing starts at the last element and ends at the first element, resulting in a reversed string.
Some other ways to reverse a string:
word = "hello"
reversed_word1 = word[-1: :-1]
reversed_word2 = word[len(word)-1: :-1]
reversed_word3 = word[:-len(word)-1 :-1]
One thing you should note about the slicing notation a[i:j:k]
is that omitting i
and j
doesn't always mean that i
will become 0
and j
will become len(s)
. It depends upon the sign of k
. By default k
is +1
.
k
is +ve then the default value of i
is 0
(start from the beginning). If it is -ve then the default value of i
is -1
(start from the end). k
is +ve then the default value of j
is len(s)
(stop at the end). If it is -ve then the default value of j
is -(len(s)+1)
(stop at the beginning). Now you can explain your students how Hello[::-1]
prints olleH
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With