little programming probleme

Eddie Corns eddie at holyrood.ed.ac.uk
Thu Mar 13 12:34:07 EST 2003


Jonas Geiregat <kemu at sdf-eu.org> writes:

>I have a string and I want to delete all comments , comments start with a #

>here is my code
>conf is my string where I want to delete comments I think the probleme 
>is that if he finds a comment he delete's the element of the list but 
>then he can't loop true that element anymore so I should break the loop 
>and start the first one again but I don't know how if it could be any 
>help I added my error code un the code


>chunk = string.split(conf,"\n")
>                 for i in range(len(chunk)):
>                         for x in range(len(chunk[i])):
>                                 if chunk[i][x] == "#":
>                                         print chunk[i]



conf = '\n'.join([x.split('#')[0].strip() for x in conf.split('\n')])


Will remove all comments and reconstruct whole string.  This assumes comments
can start anywhere on the line.  Since your code doesn't seem to match what
you say you're trying to do I'm guessing that's what you want.

In essence, it's easier to build a new string by extracting the bits you want
from the old string and joining them rather than deleting substrings from the
original.


Also when iterating over a list you can just use:

for item in list:
  do something with item

rather than:

for i in range(len(list)):
  do something with list[i]

So the longer version of above is:

tmp_string = ''
for line in conf.split('\n'):
    tmp_string += line.split('#')[0].strip()
conf = tmp_string

where line.split('#')[0] extracts the portion before the '#' or the whole
string if there is none.

Eddie




More information about the Python-list mailing list