Fiodor
Fiodor

Reputation: 806

For (not foreach) loop in Python

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

Answers (5)

poke
poke

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

Christian Tapia
Christian Tapia

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

chepner
chepner

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

jeff_kile
jeff_kile

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

barak manos
barak manos

Reputation: 30136

Try:

for i in range(0,some_string_length):
    # do something...

Upvotes: 1

Related Questions