Nearby lessons
44 of 108Python - For Loop with String
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
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Sample Output 1 Enter String : Python The Number of Characters : 6 Sample Output 2 Enter String : Durga Soft The Number of Characters : 11
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
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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
Important Points - String
- A string is treated as a sequence of characters.
- The
forloop reads one character at a time. - The loop continues until all characters are processed.
- Spaces are also treated as characters.
String Summary
| Statement | Description |
|---|---|
for x in s: |
Iterates through every character in the string. |
print(x) |
Prints one character per line. |
print(x, end=' ') |
Prints all characters on the same line. |
| Counter Variable | Counts the total number of characters. |
| Index Variable | Displays the character position. |
Important Notes
- The
forloop processes one character at a time. - Every character, including spaces, is processed.
- The
endparameter changes how the output is displayed. - A counter variable can be used to count characters.
- An index variable can be used to display both the character and its position.
Keep Going!Python - If Else