[Tutor] String.find won't - why?
Michael P. Reilly
arcege@speakeasy.net
Mon, 29 Oct 2001 07:44:35 -0500
On Mon, Oct 29, 2001 at 12:04:17AM +0100, Danny Kohn wrote:
> Am trying to remove all 0D 0A (Hex). Thought this was done through the following while loop.
> The file is attached.
> 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.
[other code snipped]
>
> i=0
> a = ''
> while i < len(text):
> pos = string.find(text[i:], '\n')
> print pos
> if pos > 0:
> a = a + text[i:pos]
> print a
> print
> i = i + pos + 1
In addition to Remco's comments, the find function also takes an optional
third argument which is the starting place.
i = 0
a = ''
while i < len(text):
pos = string.find(text, '\n', i)
# now, pos is either -1 or greater than i
print pos
if pos > 0:
a = a + text[i:pos]
print a
print
else:
break # no more newlines found
i = pos + 1
Since the new position is based on the previous position, we will always
get a proper substring (unless you get a -1 ;), this also means that
the new position can be used directly for the next time around.
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |
| Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html |