[Tutor] String Replace.....
Remco Gerlich
scarblac@pino.selwerd.nl
Mon, 29 Jan 2001 00:28:21 +0100
I had written a more detailed reply first, but accidentally sent it to
Sheila King. Her "SpamCop" system blocked my mail, giving me an URL to open
it up that didn't work... I'm a bit irritated now and will only give short
comments:
On Sun, Jan 28, 2001 at 01:31:01PM -0800, Sheila King wrote:
> I'm only a Python newbie, myself, but I've done a fair number of scripts with
> strings in them, and I've never used '\012' in my code, only '\n'.
>
> Maybe, try replacing the "\012" in your code with "\n" ???
Try it in the interpreter:
>>> "\n"
"\012"
They're the same thing.
> :## Turn Text into HTML
> :
> : def htmlize(self):
> : viewdiary = open("c:\diary.txt", 'r')
> : print viewdiary
> : print "---------------"
> : L = viewdiary.readlines()
> : print L
> : modified_str = string.replace(L, "\012", "<br>" )
> : print modified_str
> : viewdiary.close
> :
> :and the error I'm getting
> :
> :<open file 'c:\diary.txt', mode 'r' at 00B42920>
> :---------------
> :['this is a test\012', 'this is another test\012', 'one more test\012']
> :Exception in Tkinter callback
> :Traceback (most recent call last):
> : File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__
> : return apply(self.func, args)
> : File "C:\python-code\diary-update\diary.py", line 71, in htmlize
> : modified_str = string.replace(L, "\012", "<br>" )
> : File "c:\python20\lib\string.py", line 363, in replace
> : return s.replace(old, new, maxsplit)
> :AttributeError: replace
L is a list (result of readlines()), you try to use string.replace on a
list. Either use read() instead of readlines(), or don't use replace but
string.join("<BR>") to put the lines back together.
Or put the whole thing between <pre> and </pre> tags.
--
Remco Gerlich