0

Is there any kind of algorithm that you can apply to understand how Python will slice and output a sting?

I have

a="what's up"

And let's say I slice it like this:

print(a[-2:-9:-1])

So it gives me "u s'tah"

But what exactly does Python do first and last when slicing a string? Like, does it reverse a string first and then slice it, etc.?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    All your questions (including the one you deleted just now) seem to be variations of the same theme. Perhaps retreat to reading existing materials until you have a _specific,_ _concrete_ question about this. – tripleee Apr 23 '22 at 16:15
  • 1
    Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – jonrsharpe Apr 23 '22 at 16:16
  • @tripleee Yes, they are. I'm just bad at putting all my requests into one precise, well-organized question. [This](https://stackoverflow.com/questions/5798136/python-reverse-stride-slicing?noredirect=1&lq=1) one is the closest to what I try to understand. But it seems I just don't understand the topic completely, or I'm extremely confused. – imstuckwithsumfindumbsoplshelp Apr 23 '22 at 17:49

1 Answers1

2

Reference to Python - Slicing Strings (w3schools.com)

Reversing a list using slice notation

a="what's up"
print(a[-2:-9:-1]) - a[(start, end , step)]
  • start: "u" in "what's up" (position -2)

  • end: "h" in "what's up" (position -9)

  • step: step in single character in reverse direction (-1)

So, the output would be "u s'tah"

  print(a[-2:-9:-1]) # u s'tah
    print(a[-2:-9:-2]) # usth
    print(a[-2:-9:-3]) # u'h
tripleee
  • 175,061
  • 34
  • 275
  • 318
Eddie Wong
  • 36
  • 3