1

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?

2
  • 1
    Why don't you show the actual data you need to iterate over and how you want to use it? Commented Feb 8, 2014 at 0:05
  • 1
    You can try build your own C-style for loop in Python, but I really can't see why. Commented Feb 8, 2014 at 0:06

5 Answers 5

10

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):
    …
Sign up to request clarification or add additional context in comments.

Comments

5
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.

Comments

1

Try:

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

Comments

0

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

Comments

0

If you have a string s:

s = "some string"

you can do this:

for i in range(len(s)):
    print i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.