String Replacement

Bob Gailer bgailer at alum.rpi.edu
Fri Aug 1 22:32:49 EDT 2003


At 03:00 PM 8/1/2003 -0700, Fazer wrote:
>[snip] I am sort of confused in
>using the string modules and its functions/modules to replace the \n
>with <br>.  I import the string module and I am not soo sure on how to
>do the replacing.
>
>Here's how my code sort of likes:
>
>import string
>string.replace(DataFromDatabase, "\n", "<br>")
>
>Unfortunately, it doesn't work.

Actually, it does work. Just not in the way you expect. Read the 
documentation:replace(old, new[, maxsplit])
Return a copy of the string with all occurrences of substring old replaced 
by new....
string.replace is returning the altered copy; your program is not doing 
anything with it.

What you want is to take the returned value and assign it to DataFromDatabase:
DataFromDatabase = string.replace(DataFromDatabase, "\n", "<br>")

BUT also realize that most of the string module functions are now string 
methods, so it is possible (and simpler) to write:
DataFromDatabase = DataFromDatabase.replace("\n", "<br>")

If you develop further needs for substitutions you'd want to consider 
alternate techniques rather than stacking up a lot of replace calls.

OTOH some methods do operate "in-place" such as listobject.sort() and 
listobject.reverse().

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20030801/30b4b0b7/attachment.html>
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003


More information about the Python-list mailing list