Sign in to follow this  
Chozo

Python for loop question

Recommended Posts

Chozo    176
I've written parsers in C before that would do something like this:
char* str = "Hello {{name}}";
for(int i=0; i<strlen(str); ++i) {
    if(str[i] == '{') {
        if(str[i+1] == '{') {
            i++;
            do_something();
        }
    }
}
So it ends up skipping over that second character when the for loop iteration var is incremented. I'm trying to do something similar in python, but obviously it's not working because of the way I'm doing the loop over the list:
str = "Hello {{name}}"
for i in range(len(str)):
    if str[i] == '{':
        if str[i+1] == '{':
            i += 1
            do_something()
Is there a way to make this work? Thanks in advance.

Share this post


Link to post
Share on other sites
eedok    982
I'm not entirely sure what you're wanting to do, but by the looks of your if statements it looks like you should be looking into regular expressions.

Share this post


Link to post
Share on other sites
Chozo    176
Yeah, I think that's probably what I'm going to end up doing. I'm basically just going to be replacing the {{name}} with some value in a variable. Now that I've run into this though, I'm curious about how it could be done.

The basic goal here is just looking ahead when parsing the string, seeing that the next character is another { and moving the next iteration to the following character.

Share this post


Link to post
Share on other sites
Chozo    176
Well, I won't know ahead of time what the variables to replace will be, so a regular expression will probably be better. I'm still just more curious about how to get a for loop to skip values now that I've run across trying to do it.

Share this post


Link to post
Share on other sites
Oluseyi    2103
Quote:
Original post by Chozo
I'm still just more curious about how to get a for loop to skip values now that I've run across trying to do it.

Set a flag or counter and use continue.

lookaheadCounter = 0
for i in sequence:
if lookaheadCounter:
lookaheadCounter -= 1
continue

if lookaheadCondition:
lookaheadCounter = iterations_to_skip

Share this post


Link to post
Share on other sites
Hollower    685
In Python for loops iterate over a sequence, binding the variable to each element in the sequence. A range is basically a list of numbers, ie. range(5) is equivelent to [0, 1, 2, 3, 4]. Altering i within the loop will have no effect once the next iteration begins because it will be rebound to the next element in the sequence. To skip one iteration ahead you would use the continue statement, as in Oluseyi's example.

Because of the binding mechanics I just described, we usually iterate directly over the sequence rather than over the range of its indices as in C. A string is an iterable sequence in Python. Example:

for char in string:
if char == '{':
# etc, etc.

By the way, for string formatting you don't need to know in advance what the variable name is. You only need to be sure there is a key for it in the provided dictionary. Example:

profile = {"name":"Chozo", "health":100, "ammo":20 }
greet = "Hello %(name)s."
status = "Your health is %(health)d and you have %(ammo)d rounds."
print greet % profile
print status % profile

If the key is not gauranteed to exist you can handle the KeyError exception.
try:
output = greet % profile
except KeyError:
output = greet % {"name":"noname"}

You can also get your local variables in dictionary form:
name = "Chozo"
print greet % locals()


(ps. you shouldn't use str as a variable name because that just happens to the built-in type name for strings)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this