String Slicing

String Slicing

We can access a part of a string by its position starting from 0. To do so we need to put the position number inside [sqaure brackets] after the string.

-------------------------------------------

code:-

mystr = "Hello World"

print(mystr[3])

print(mystr[6])

output:-

l

W

-------------------------------------------

***Note that positions always start from 0 and not 1.***

In the above example, the positions of the string are:-
H         - 0
e          - 1
l           - 2
l           - 3
o          - 4
            - 5
W        - 6
o          - 7
r          - 8
l          - 9
d          - 10

To get a long part out of a string you can give two positions like [5:9] which will give you a string taken from the main string's 5th to 9th position.

-------------------------------------------

code:-

mystr = "Hello World"

print(mystr[0:5])

output:-

Hello

-------------------------------------------


Comments

Popular posts from this blog

Comments

#9 - String Concatenation

#1- Let's Learn Python In the least possible time