views:

5735

answers:

3

While editing someone else's abandoned Python script, I was trying to use

mystring.find("\n", i)

to get the index of the next newline in a string. But this consistently returns -1 (even when I try using "\r\n" instead of "\n"). I know there are newlines in the string, because I had just loaded it from a file. I am not very familiar with Python; am I missing something obvious?


EDIT: Yes, I tried printing out the string. It looks something like this:

expirydate = { year = 1820 }
minimum = { 500 }
extra = { }

The person who originally wrote the script apparently decided that it's better to load the entire file into memory before parsing it.


EDIT2: repr(mystring) looks like this (truncated again):

 expirydate = { year = 1820 }\n minimum = { 500 }\n extra = { }\n


EDIT3: As some people suspected, I was misunderstanding the input. Apparently, it was actually searching in a substring of the full input, and the substring simply didn't have a newline. Unfortunately, this still doesn't explain why the script doesn't work, but it helps me get a little closer. I'm closing this question and voting up everyone who took the time to answer. :)

+2  A: 

How are you reading the file? Some methods strip newlines when you use them. If you print mystring, you should have one blank line after it (which will mean 2 newlines).

Edit: What is i equal to? You probably don't need it there.

Harley
I guess the i was to make it a little faster. This program is a rather brittle parser for save game files that can be rather large. How brittle? I changed the whitespace format of the saves and it no longer works.
Michael Myers
i will just tell the .find where to start, if it's not there it will start at 0, which is probably what you want. Also look into reading through the files with readlines()
Harley
Yeah, I know you can read by lines, but this script is a little too big for me to attempt a rewrite (especially since I don't really know Python).
Michael Myers
+3  A: 

I think your i has a wrong value

>>> "one\ntwo".find('\n')
3
pixelbeat
This looks like i > 60 which in this case will cause "find" to start it's search after the last '\n' in your string.
mhawke
+2  A: 

I am guessing you are trying to split file at new lines.

Python has a builtin function split

>>>txt = "My \n long \n new line \n delimited \n file"
>>>print
My 
 long 
 new line 
 delimited 
 file
>>> txt.split('\n')
['My ', ' long ', ' new line ', ' delimited ', ' file']
Luka Marinko
Actually, it was trying to find the first instance of a space ' ', or a '\n' if that occurred first. But thanks for the info.
Michael Myers