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
Answer from hasen on Stack OverflowAs 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
How do you make a program iterate over a string (which is already a variable) a set amount of times?
How to iterate over every line of a string in Python?
iterating over a list of strings
Is there a way to "loop" through an integer?
I'm new to python and one of the exercises they gave us at school requires me to make the program iterate over a string a set amount of times.
The issue is that if I use the "for" loop (aka: for i in range()), there is nowhere to put which variable I want it to iterate over, and if I put "for i in (variable)", I can't tell it how many times it needs to do it and just ends up iterating the whole string. Any input on the matter is appreciated.
I'm trying to loop over a list of strings. So how can I continue with iterating the inner loop with the outer Index.
l1 = [str1, str2, str3,str4,str5,str6,str7,str8,str9]
temp = []
for str in l1:
If re.search(r'.*4',str) :
for str in l1: if str is str8: break else: temp.append(str)
Output : temp = [ str5,str6,str7]
The above code is the pseudo code. I want to append strings to temp, if they match particular pattern.