[Tutor] String.find won't - why?

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 29 Oct 2001 00:13:31 +0100


On  0, Danny Kohn <danny.kohn@systematik.se> wrote:
> Hi again.
> Thanks for all the comments on the readline(s) issue. I have understood this fully.
> But please bear with me. Unfortunally the next step in this little program is as problematic for me.
> Am trying to remove all 0D 0A (Hex). Thought this was done through the following while loop.
> The file is attached.

0D 0A? That's CRLF right, a newline on Windows/DOS. Ok.

> The first round things works nicely. The 0D 0A (Hex) is found and removed. Pos is correctly 142.
> The second round things behave more strangely. Pos will get a wrong value (178) but there just is no 0D 0A (Hex) there and so the i:pos string will get to short.
> Running w2k. Why on earth is this behaving wrongly?
> 
> t = open('d:/Experiment.txt', 'r')
> 
> text = t.read()    # Read text
> t.close()
> 
> print text
> print
> 
> i=0
> a =  ''
> while i < len(text):
> 	pos = string.find(text[i:], '\n')

Here, pos gets a position relative to text[i:].

> 	print pos
> 	if pos > 0:
> 		a = a + text[i:pos]

Here you use pos as an index in the whole string.

So you meant a = a + text[i:i+pos].

The reason this works the first time is that it's the same thing with i=0.

> 		print a
> 		print
> 	i = i + pos + 1
> 
> /Danny


Btw, the whole loop can be written

a = string.replace(text, '\n', '')

Hope this helps :)

-- 
Remco Gerlich