Nearby lessons
45 of 159Python - 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
Note
The blank line in the output represents the space character between Sunny and Leone.
Example 2 - Print Characters One by One
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
Explanation
The end=' ' argument prints all characters on the same line with a space between them.
Example 4 - Count Characters in a String
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
📝 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 QuestionsProgress: 0 / 8