Home > Net >  How does Python execute string slicing?
How does Python execute string slicing?

Time:04-23

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

CodePudding user response:

Rerference to Python - Slicing Strings: https://www.w3schools.com/python/python_strings_slicing.asp

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
  • Related