[Python-Dev] PEP 3101 Update
Edward Loper
edloper at gradient.cis.upenn.edu
Mon May 8 13:58:55 CEST 2006
Steven Bethard wrote:
> On 5/7/06, Edward Loper <edloper at gradient.cis.upenn.edu> wrote:
>> Talin wrote:
>>> Braces can be escaped using a backslash:
>>>
>>> "My name is {0} :-\{\}".format('Fred')
>>>
>>> Which would produce:
>>>
>>> "My name is Fred :-{}"
>> Do backslashes also need to be backslashed then? If not, then what is
>> the translation of this:?
>>
>> r'abc\{%s\}' % 'x'
>
> I believe the proposal is taking advantage of the fact that '\{' is
> not interpreted as an escape sequence -- it is interpreted as a
> literal backslash followed by an open brace:
Yes, I knew that fact, but it's not related to my question. The basic
issue is, that if you have a quote character ('\\'), then you usually
need to be able to quote that quote character ('\\\\') in at least some
contexts.
So I'll try again with a different example. I'll avoid using raw
strings, just because doing so seems to have confused a couple people
about what my question is about. Let's say I have a program now that
contains the following line:
print 'Foo\\%s' % x
And I'd like to translate that to use str.format. How do I do it? If I
just replace %s with {0} then I get:
print 'Foo\\{0}'.format(x)
but this will presumably raise an exception, since the '\\{' (which is
identical to '\{') gets treated as a quoted brace, and the '}' is
unmatched. If it were possible to backslash backslashes, then I could do:
print 'Foo\\\\{1}' % x
(which can also be spelled r'Foo\\{1}' -- i.e., the string now contains
two backslash characters).
But I haven't seen any mention of backslashing backslashes so far.
-Edward
More information about the Python-Dev
mailing list