Image

Anyone Can Code.





Image

Traversing a String

Sammarth Kumar



Traversing means accessing the characters of a string. We can do so using a for loop or a while loop.

Traversing using for:

1
2
3
string = "Q-Programming"
for character in string:
    print(character)

Output

Q
-
P
r
o
g
r
a
m
m
i
n
g

Traversing using while:

1
2
3
4
5
string = "Q-Programming"
index = 0
while index < len(string):
    print(string[index])
    index += 1

Output

Q
-
P
r
o
g
r
a
m
m
i
n
g

Here we used len() to get the total number of characters in the string. The while loop will access all the characters of the string from index 0 to index len(string) -1 , which is all the characters of the string.


That's it for this tutorial! Scroll up and click on Next for the next tutorial!

For information on how you can use this information, please refer to our Terms of Use


Copyright © 2020, Q-Programming | Created by Arjun Sodhi, Balpreet Juneja and Sammarth Kumar | Developed and Designed by Sammarth Kumar