Slice Strings in Python| Python beginner tutorial

Published: 09 February 2024
on channel: edtech by meera
10
0

Python beginner tutorial to show you how to slice strings in Python3. Cor slicing you need to use a square bracket with first parameter indicating the index of the string at which the slicing starts and the second parameter indicating the index of the string at which the slicing ends, note, the second parameter is showing the indec number that is not included. with a colon between the two parameters.
for example if i slice [0:5] from a string "greetings" then slice starts from index 0 and stops at 5 but 5 is exclusive meaning, the output extracted characters are from index 0 all the way to index 4, as index 5 is exclusive and so, the extracted value will be "greet"
Here , "g" is at index 0 and "t" at index 4 so extracted end point will exclude one less than the second parameter.
If I slice with [1:7] then extracted output from the string "greeting" is "reetin" as slice starts from index 1 which is "r" and ends right before index 7, that is, index 6 by extracting from index 1 all the way till index 6, hence extracting the string, "reetin" , we know, index 7 is at "greeting"
If I slice [0:] then as the second parameter is not mentioned, it defaults to the last index of the string, so, here the extracted value is "greeting"

if I slice using [:8] where we haven't mentioned the first parameter, then, it defaults to 0 index,meaning slicing starts from 0 index and stops at index 7,(one short of 8)
extracted value is "greeting"

For a string, "greetings"
If I slice with [-4: -1] then slice starts from reverse, that is end of the string, "i" as index -4 indicates position for character "i" and continues to index -1, but second parameter that is index -1 is exclusive, so,
slicing stops at one short of -1 which is -2 as we all know that -2 is less than -1. so extracted value from "greetings" is "ing"


On this page of the site you can watch the video online Slice Strings in Python| Python beginner tutorial with a duration of hours minute second in good quality, which was uploaded by the user edtech by meera 09 February 2024, share the link with friends and acquaintances, this video has already been watched 10 times on youtube and it was liked by 0 viewers. Enjoy your viewing!