1 Replies - 1093 Views - Last Post: 01 December 2010 - 07:58 AM Rate Topic: -----

#1 Guest__xStash*


Reputation:

Read next line function keeps reading the same line

Posted 30 November 2010 - 09:59 PM

Hello

I have a function that reads a string & identifies the next two endline characters. Then the function should return the text that lies within those next two enline characters.

My Problem:
But my function is not reading past the first 2 endline characters which is making reading the next line difficult.


If you look at my simple code below you should see how it works & below that is the output that shows how the functions fails:
def get_line_of_code( code_str, begin_index ):
    """ Post: Return the next line of code after begin_index's next
              '\n' character """

    line_start = code_str.find( '\n', begin_index    )
    line_end   = code_str.find( '\n', line_start + 1 )

    if line_end <= -1:

        line_end = len( code_str )

    #print "In get_line_of_code(): looking at line [" + code_str[ line_start : line_end ].replace('\n','/N') +"]"
    return ( code_str[ line_start : line_end ].replace('\n','').expandtabs(4), line_end )


## Test
k = " string \nbtring \nctring \ndtring \netring \nftring \ngtring \nhtring \nitring \njtring \nktring \nltring \n"
x = 0


for x in range(k.count('\n')):

    ln_info = get_line_of_code( k, x )
    ln      = ln_info[0]
    x       = ln_info[1]
    print ln



Incorrect output that occurs

Quote

btring
btring
btring
btring
btring
btring
btring
btring
btring
ctring
ctring
ctring


The correct output should be

Quote

btring
ctring
dtring
etring
ftring
gtring
htring
itring
jtring
ktring
ltring
mtring


Is This A Good Question/Topic? 0

Replies To: Read next line function keeps reading the same line

#2 duffman18   User is offline

  • D.I.C Head

Reputation: 15
  • View blog
  • Posts: 54
  • Joined: 20-October 10

Re: Read next line function keeps reading the same line

Posted 01 December 2010 - 07:58 AM

You have your for loop set up incorrectly. You are using the variable x for your iterations in your for loop and to store your index to start your next search. So every time the for loop goes to the next iteration the x variable you have saved is getting overwritten. What you need to do is change the variable 'x' in the for loop to something else:

for i in range(k.count('\n')):
    ln_info = get_line_of_code( k, x )
    ln      = ln_info[0]
    x       = ln_info[1]
    print ln


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1