Program to display each character of a string using loops

This program shows how to display each character of a string using for and while loop

Asking user to enter any string and assigning it to a varaible

str = input('Enter any string: ')

Finding length of a string using len() function and displaying it

l = len(str)
print('Total length of a string: ',l)

Creating a variable i with zero value

i = 0

Using while loop to display each character of a string.

print('Using while loop to display characters inside string')
while i<l:
print(str[i])
i=i+1

Using for loop to display characters of a string

print('Using for loop to display characters inside string')
for s in str:
print(s)

Output

Enter any string: Python
Total length of a string:  6
Using while loop to characters inside string
P
y
t
h
o
n
Using for loop to display characters inside string
P
y
t
h
o
n

Complete Code

str = input('Enter any string: ')
l = len(str)
print('Total length of a string: ',l)
i = 0
print('Using while loop to display characters inside string')
while i<l:
print(str[i])
i=i+1

print('Using for loop to display characters inside string')
for s in str:
print(s)
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s