Printing one character at a time from a string, using the while loop
I'm quite sure, that the internet is full of python while-loops, but one example:
i=0
while i < len(text):
print text[i]
i += 1
Strings can have for loops to:
for a in string:
print a
Other answers have already given you the code you need to iterate though a string using a while
loop (or a for
loop) but I thought it might be useful to explain the difference between the two types of loops.
while
loops repeat some code until a certain condition is met. For example:
import random
sum = 0
while sum < 100:
sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
print sum
This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.
for
loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java for
loops usually use some sort of a counter variable (below I use i
), and generally makes the similarity between while
and for
loops much more explicit.
for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
System.out.println(i);
}
This loop will run exactly 10 times. This is just a nicer way to write this:
int i = 0;
while (i < 10) { //until i is 10
System.out.println(i);
i++; //add one to i
}
The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:
for item in myList:
print item
or
for character in myString:
print character
However, you didn't want to use a for
loop. In that case, you'll need to look at each character using its index. Like this:
print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.
Knowing that you can make a for
loop using only a while
loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a while
loop.
HOWEVER in general you'd use a for
loop in this situation because it's easier to read.