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
Answer from Gjordis on Stack OverflowHow to print each letter on new line?
Iterating each character in a string using Python - Stack Overflow
Python: How can you print strings one character at a time?
how do i print while loop outputs on the same line?
Alternatively...
Instead of printing in the loop, append what you want to print to a list.
Then AFTER the loop, print out the entire list. Something like join() is great for inserting commas without needing to have a special case for "except after the last one".
result = []
for idx in range(10):
result.append("n{}".format(idx))
print(",".join(result)) More on reddit.com Doing some revision, how would I do this:
Using a while loop, write a Python program that displays each of the characters in “Hello” on a new line, with the letter number before each character, starting at 1. e.g.
1: H
2: e
3: l etc.
This is what I have so far:
w = input("Please enter Word: ")
list = w.split()
print(list)for r in list: print(r, '\t')
I can get it to split sentences but not words.
As Johannes pointed out,
for c in "string":
#do something with c
You can iterate pretty much anything in python using the for loop construct,
for example, open("file.txt") returns a file object (and opens the file), iterating over it iterates over lines in that file
with open(filename) as f:
for line in f:
# do something with line
If that seems like magic, well it kinda is, but the idea behind it is really simple.
There's a simple iterator protocol that can be applied to any kind of object to make the for loop work on it.
Simply implement an iterator that defines a next() method, and implement an __iter__ method on a class to make it iterable. (the __iter__ of course, should return an iterator object, that is, an object that defines next())
See official documentation
If you need access to the index as you iterate through the string, use enumerate():
for index, character in enumerate('test'):
print(index, character)
...
0 t
1 e
2 s
3 t