Class XI : Python Strings

How to access characters in a string?

We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError.
The index must be an integer. We can’t use float or other types, this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator (colon).

Example:
n=”computer”

Positive index

0

1

2

3

4

5

6

7

c

o

m

p

u

t

e

r

n=”computer”
print(n)
print(n[0])
print(n[2])
print(n[4])
print(n[5])
print(n[7])

output:

computer
c
m
u
t
r

Example:
n1=”catalyst”

Positive index

0

1

2

3

4

5

6

7

c

a

t

a

l

y

s

t

n1=’catalyst’
print(n1)
print(n1[0])
print(n1[2])
print(n1[4])
print(n1[5])
print(n1[7])

output:

catalyst
c
t
l
y
t