Iterating Through String
1.
Python program to take input for a string and display it in the given format. (iterate through string)
n=”hello”
h
e
l
l
o
Sol:
#solution using for loop
n=input("Enter any string ")
for i in n:
print(i)
#using while loop
n=input("Enter any string ")
i=0
while(i<len(n)):
print(n[i])
i=i+1
2.
Python program to take input for a string and display it in the given format. (iterate through string)
n=”hello”
Output:
hello
Sol:
#using for loop
n=input("Enter any string ")
for i in n:
print(i,end=' ')
#using while loop
n=input("Enter any string ")
i=0
while(i<len(n)):
print(n[i],end=' ')
i=i+1
3.
Python program to traverse a string and display total upper case alphabets
Example Output:
n=”HeLLo”
Output:
total upper case alphabets 3
Sol:
#using for loop
n=input("Enter any string ")
u=0
for i in n:
print(i)
if(i>='A' and i<='Z'):
u=u+1
print("total upper case alphabets ",u)
#using while loop
n=input("Enter any string ")
u=0
i=0
while(i<len(n)):
print(n[i])
if(n[i]>='A' and n[i]<='Z'):
u=u+1
i=i+1
print("total upper case alphabets ",u)
4.
Python program to traverse a string and display total lower case alphabets in the string
Example:
n=”heLLo”
output:
total lower case alphabets 3
Sol:
#using for loop
n=input("Enter any string ")
u=0
for i in n:
print(i)
if(i>='a' and i<='z'):
u=u+1
print("total lower case alphabets ",u)
#using while loop
n=input("Enter any string ")
u=0
i=0
while(i<len(n)):
print(n[i])
if(n[i]>='a' and n[i]<='z'):
u=u+1
i=i+1
print("total lower case alphabets ",u)
5.
Python program to traverse a string and display total digits in the string
Example Output:
n=”he123o”
output:
total digits 3
Sol:
#using for loop
n=input("Enter any string ")
d=0
for i in n:
print(i)
if(i>='0' and i<='9'):
d=d+1
print("total digits ",d)
#using while loop
n=input("Enter any string ")
d=0
i=0
while(i<len(n)):
print(n[i])
if(n[i]>='a' and n[i]<='z'):
d=d+1
i=i+1
print("total digits ",d)