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.?

3
  • 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. Commented Apr 23, 2022 at 16:15
  • 1
    Does this answer your question? Understanding slicing Commented Apr 23, 2022 at 16:16
  • @tripleee Yes, they are. I'm just bad at putting all my requests into one precise, well-organized question. This 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. Commented Apr 23, 2022 at 17:49

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.