Reputation: 806
I need to make a simple python script, but as I mostly do PHP / C++ I find it hard to manage myself without simple for loops. Let's say I have a code:
for(int i = 0; i < some_string_length; i++)
{
//do something...
}
As you can see it simply goes as many times as many letters I have in my string. Of course, I could do this in a while loop, but that has an issue. I have to either create a variable outside of the loop which will make it global or create it inside the loop, but this variable's value can't be used in the argument of loop.
Wrong:
while(i < some_string_length)
{
i = something; //declaring i for the first time
i++;
}
As you can see it doesn't make sense at all. So how can I do this?
Upvotes: 1
Views: 1297
Reputation: 387755
The construct from other languages
for (int i = start; i < stop; i += step) { … }
translates directly into a Python for loop over a range
:
for i in range(start, stop, step):
…
By default, step
is 1, so you don’t need to specify it for i++
. start
defaults to zero, so you can also leave that out, if you start with i = 0
:
for i in range(stop): # the same as `for (int i = 0; i < stop; i++)`
…
So, if you want to iterate i
over the length of a string, you can just do this:
for i in range(len(my_string)):
…
Usually, you would want to access the character of that string though, so you can just iterate over the characters directly:
for char in my_string:
…
Or, if you really do need the index as well, you can use enumerate
to get both:
for i, char in enumerate(my_string):
…
Upvotes: 10
Reputation: 34146
If you have a string s
:
s = "some string"
you can do this:
for i in range(len(s)):
print i
Upvotes: 0
Reputation: 531285
for i, item in enumerate(some_string):
# i is the index, item is the actual element
I think you'd be surprised how rarely you actually need i
, though. You're better off learning how to use Python idioms, rather than forcing yourself to write PHP/C++ code in Python.
Upvotes: 5
Reputation: 1835
I think you want to use the range
function
for x in range(0, 3):
print "x: %d" (x)
https://wiki.python.org/moin/ForLoop
Upvotes: 0