Indexing

Every 
character 
in 
a 
string 
is 
given 
a 
number 
that 
is 
called 
an 
index
.
We 
can 
access 
each 
character 
of 
a 
string 
with 
help 
of 
these 
indices.
The 
first 
character 
has 
index 
0
, 
the 
second 
character 
has 
index 
1
, 
and 
so 
on.
string_name[index number]
greeting = ""Bonjour""
# B=0, o=1, n=2, j=3, o=4, u=5, r=6
print(greeting[6])

index() function

index()
 
function 
is 
used 
to 
get 
the 
index 
number 
of 
a 
particular 
character.
If 
the 
character 
occurs 
more 
than 
once 
in 
the 
string, 
the 
index 
of 
the 
first
 
occurrence 
is 
given.
string.index(value, start, end)

#value - The character to search for.

#start (Optional) - Index number to start the search from. Default is 0.

#end (Optional) - Index number to end the search at. Default is to the end of the string.
prince_name = "Prince Poppy"
print(prince_name.index("i"))
print(prince_name.index("p"))

Negative Indexing

Python 
numbers 
the 
characters 
of 
a 
string 
in 
two 
ways, 
forward
 
and 
backward
.
While 
numbering 
backward, 
Python 
gives 
the 
characters 
a 
negative 
index 
starting 
from 
-1
 
for 
the 
last 
character 
in 
the 
string.
funny_prince = 'Prince Poppy'
print(funny_prince[-1])
print(funny_prince[-4])

Strings are immutable

Python 
does 
not 
allow 
to 
change 
any 
character 
in 
a 
string.
greeting = "Hey, man!"
greeting[0] = "C"
print(greeting)

Slicing a string

Slicing
 
- 
We 
get 
a 
part 
of 
the 
string 
from 
the 
starting 
index 
to 
the 
character 
previous 
to 
the 
ending 
index.
string_name[starting index:ending index]
We 
can 
also 
slice 
a 
string 
up 
to 
the 
last 
letter.
By 
not 
specifying 
the 
ending 
index, 
Python 
automatically 
takes 
the 
last 
letter 
of 
the 
string 
as 
the 
endpoint.
string_name[starting index:]
Similarly 
not 
giving 
a 
starting 
index, 
means 
Python 
will 
take 
the 
index 
of 
the 
first 
letter 
in 
the 
string.
string_name[:ending index]
Similarly 
not 
giving 
any 
index 
means 
Python 
will 
take 
the 
entire 
string.
string_name[:]
Python 
can 
also 
skip 
letters 
in 
between 
while 
slicing. 
We 
use 
two 
colons 
for 
that.
string_name[::step]
#If step is 3, python will print every third character only.
word = 'helipad'
print(word[2:6])

word = 'helipad'
print(word[2:])

word = 'helipad'
print(word[:6])

word = 'helipad'
print(word[:])

word = 'helipad'
print(word[::2])
#python prints every second character

Length of the string - len()

Python 
counts
 
and 
returns 
the 
number 
of 
characters
 
in 
a 
string 
using 
len()
 
function.
len(string_variable)
word = 'helipad'
print(len(word))

word = 'helipad'
length = len(word)
print(word[2:length]
#we saved the length of the word using the len() function, then we sliced the word from 2 to 7.