String Slicing and Picking sub-string in Python3

Picking Sub-String

Now, we will pick individual character or sub-string from string.
So, lets see,



You might be thinking, why is that ‘g’, because we specified the third character, so shouldn’t that be counting from left to right, ‘B’ is the first character, ‘e’ is the second and ‘n’ is the third and in actual fact ‘g’ is the fourth character. Now you are thinking then why we say that ‘g’ is the third character. It’s actually usual for programming languages to start counting at zero and not at one. So that tiger zero is ‘B’. So we’ll actually go and see that,



So there’s 12 character in ‘Bengal Tiger’, numbered from 0 to 11 and if we try to print 12 number character, then you’ll get an error.


The other thing as you can do is count backwards.



So, what’s happened is that it started here at position zero and goes to negative one. Negative one goes all to the way to the end of the string and starts counting from end. So we get the letter, which is the last character from the string.

String Slicing


In this, instead of providing one number, provide two numbers separated by a colon.



Now, we got ‘Benga’ which is the length of five characters starting at position zero. So the first number in the string to start, printing out, and the fifth is how many characters to actually print out.
In the slice, if the first number, which is before the colon is not there, then the slice is going to start from the beginning of the string.



And if the second number, which is after the colon is not there, then the slice going to end of the string.


Comments

Popular posts from this blog

Variable in Python3

Integers and Float in Python3