Nearby lessons

45 of 159

Python - For Loop with String

📌 What You Will Learn
  • Understand how a for loop treats a string as a sequence of characters
  • Print each character of a string one by one
  • Print characters on the same line using the end argument
  • Count the total number of characters in a string with a counter variable
  • Display the index position of each character

for Loop with String

If we want to execute an action for every character present in a string, we can use the for loop.

A string is treated as a sequence of characters.

Example 1 - Print Characters Present in a String

🐍Code Cell
1s = "Sunny Leone"
2 
3for x in s:
4 print(x)
Output
S
u
n
n
y

L
e
o
n
e

Note

The blank line in the output represents the space character between Sunny and Leone.

Example 2 - Print Characters One by One

🐍Code Cell
1name = input("Enter Name : ")
2 
3for x in name:
4 print(x)
Output
Sample Output 1

Enter Name : Durga

D
u
r
g
a


Sample Output 2

Enter Name : Python

P
y
t
h
o
n

Explanation

The loop reads one character at a time from the given string.

Each character is printed on a new line.

Example 3 - Print Characters on the Same Line

🐍Code Cell
1s = "Python"
2 
3for x in s:
4 print(x, end=' ')
Output
P y t h o n

Explanation

The end=' ' argument prints all characters on the same line with a space between them.

Example 4 - Count Characters in a String

🐍Code Cell
1s = input("Enter String : ")
2 
3count = 0
4 
5for x in s:
6 count = count + 1
7 
8print("The Number of Characters :", count)
Output
Sample Output 1

Enter String : Python

The Number of Characters : 6


Sample Output 2

Enter String : Durga Soft

The Number of Characters : 10

Explanation

A counter variable is used to count each character while iterating through the string.

Spaces are also counted as characters.

Example 5 - Print Character with Index Position

🐍Code Cell
1s = input("Enter String : ")
2 
3i = 0
4 
5for x in s:
6 print("The Character Present at Index", i, ":", x)
7 i = i + 1
Output
Sample Output

Enter String : ABC

The Character Present at Index 0 : A
The Character Present at Index 1 : B
The Character Present at Index 2 : C
📝 Key Takeaways
  • A string is treated as a sequence of characters in a for loop
  • The end=' ' argument prints all characters on the same line
  • Spaces are also counted as characters
  • A counter variable counts every character while iterating
  • The loop continues until all characters are processed

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8