[Tutor] FW: wierd replace problem
Walter Prins
wprins at gmail.com
Tue Sep 14 11:42:49 CEST 2010
On 14 September 2010 08:38, Roelof Wobben <rwobben at hotmail.com> wrote:
>
> I understand what you mean but we're talking about a text-file which will
> be read in a string.
> So I can't escape the quotes. As far as I know I can't control how Python
> is reading a text-file with quotes.
>
>
Putting a value into a string via Python source code is not the same as
putting a value into a string by reading a file. When you read a file it's
implicit that whatever's in the file (including quotes) will end up in the
string. There's no ambiguity so no need to worry about escaping.
In Python source code however, quotes have meaning implied by context, so
you have to encode/write strings differently *in source* in order to
disambiguate your intention. In other words, when Python encounters a first
quote in source code, it interprets this as the start of a string. When it
encounters the next quote of the same type, it interprets this as the end of
the string, and so on. If you therefore want to put a quote of the same
type you're using to delineate a string inside of that same string, you need
to "escape" the quote, e.g. tell Python to not interpret the quote as it
normally would and to rather take it literally and as part of the current
string value being read. This you do by putting a backslash (e.g. \ )
before it. Of course, the same problem happens when you want to put
backslash itself in a string, so the backslash itself also need to be
escaped in order to be put inside a string in Python.
HTH
Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/2231ccc4/attachment.html>
More information about the Tutor
mailing list