The traversing or processing of each character of a string at each iteration is a very useful tool in computation. Often the program starts the execution, selects each character of a string, does something with it, and continues until the end of a program. The traversing of a string can be realized using a while loop as can be seen in the next example.
Example 1Create while loop that will in each iteration print the characters of the "Computer" string.
Solution: The first step is to assign the "Computer" string to some variable. In this example, we have assigned "Computer" to the variable named string.
Example 1Create while loop that will in each iteration print the characters of the "Computer" string.
Solution: The first step is to assign the "Computer" string to some variable. In this example, we have assigned "Computer" to the variable named string.
string = "Computer"Then we will create the variable named index and assign to it a value of 0. The index variable is a variable that will be used in the while loop and checked in each iteration if its value is less than the length of the variable string. Of course in the body of the while loop, the index variable value will be incremented at each iteration.
index = 0Then we will write the while statement with condition that the index value must be less than the length of a string variable. The while loop will execute until the condition becomes False i.e. until the index value becomes greater than the length of a string variable. In the body of the while loop, we will create a variable letter and the character from the string will be assigned to the letter variable that is accessed with rectangle brackets [] notation with index value inside. Then the letter will be shown as output using the print function and format function. The letter will be written in the form of "letter[{}] = {}".format(index, letter). The index will be placed in curly brackets, and the letter value will be placed in the second curly bracket. The last command in the while loop body is the update of the variable index which will be incremented in each iteration. The while loop is given below.
while index < len(string):The entire code created in this example is given below.
letter = string[index]
print("letter[{}] = {}".format(index, letter))
index += 1
string = "Computer"The output is given below.
index = 0
while index < len(string):
letter = string[index]
print("letter[{}] = {}".format(index, letter))
index += 1
letter[0] = C
letter[1] = o
letter[2] = m
letter[3] = p
letter[4] = u
letter[5] = t
letter[6] = e
letter[7] = r