Python Basics

How to go through every character in a string python?

Python treats a string as sequence of characters. Which means in the eyes of python, a string list of characters.

Therefore to access a character in a string we must have to call it by its index number.

Every Character in a String

With the help of for loop we can print every character of a string.

Example

sentence=”Once upon a time”

for ch in sentence:

print(ch)

Output:

O

n

c

e

 

u

p

o

n

 

a

 

t

i

m

e

Each character in a string

Alternatively by using index number also we can print all the characters of a string using for loop.

for indnum in range(0,len(sentence)):

print(sentence[indnum])

Output:

O

n

c

e

 

u

p

o

n

 

a

 

t

i

m

e