How can I iterate over a string in Python (get each character from the string, one at a time, each time through a loop)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As Johannes pointed out,
You can iterate pretty much anything in python using the
for loopconstruct,for example,
open('file.txt')returns a file object (and opens the file), iterating over it iterates over lines in that fileIf 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
forloop 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 definesnext())See official documentation