Python for loop question

Started by
5 comments, last by Hollower 16 years, 1 month ago
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 == '{') {
        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 == '{':
        if str[i+1] == '{':
            i += 1
            do_something()
Is there a way to make this work? Thanks in advance.
Advertisement
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.
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.
try something like this:
h = "Hello {{name}}"print h.replace("{{name}}","Chozo")
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.
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 = 0for i in sequence:    if lookaheadCounter:        lookaheadCounter -= 1        continue    if lookaheadCondition:        lookaheadCounter = iterations_to_skip
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 % profileprint status % profile

If the key is not gauranteed to exist you can handle the KeyError exception.
try:    output = greet % profileexcept 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)

This topic is closed to new replies.

Advertisement