rst and pypandoc

Dave Angel davea at davea.name
Mon Mar 2 18:23:05 EST 2015


On 03/02/2015 05:40 PM, alb wrote:
> Hi Dave,
>
> Dave Angel <davea at davea.name> wrote:
> []
>>>> or use a raw string:
>>>>
>>>> i = r'\\ref{fig:abc}'
>>
>> Actually that'd be:
>>     i = r'\ref{fig:abc}'
>
> Could you explain why I then see the following difference:
>
> In [56]: inp = r'\\ref{fig:abc}'

print inp
    and you should get
      \\ref{fig:abc}

>
> In [57]: print pypandoc.convert(inp, 'latex', format='rst')
> \textbackslash{}ref\{fig:abc\}
>
>
> In [58]: inp = r'\ref{fig:abc}'

print inp
     and you should get
        \ref{fig:abc}

This is NOT the same.

The rules are not arbitrary.  They're quite necessary, and it's the same 
for lots of different languages.  When in a regular literal, the 
backslash is an escape character that combines with the following 
character.  When in a raw literal, the backslash is a backslash, unless 
it's at the end of the string, in which case it's not the end of the 
string, it's an escaped quotation.  (Or something.  Just don't use 
*trailing* backslash in a raw literal)

>
> In [59]: print pypandoc.convert(inp, 'latex', format='rst')
> ref\{fig:abc\}
>
> The two results are clearly *not* the same, even though the two inp
> /claim/ to be the same...
>

When I said backslashes are not special in data read from a file, I 
should also say neither are quotes, or tabs, or anything else.  Python 
just reads them in, and stuffs them into a string object.  Newlines are 
special if you use readline(), but if you use read(), they're not 
special either (except on MSDOS compatible variants, which use two bytes 
for newline.  Even there, if you read a file in "b" mode, they're not 
special either.

So your code is going to mostly be getting strings from files, or from 
calculations, and these backslashes won't be special.  It's only in 
*testing* that you usually deal with this literal stuff.  Or in places 
where the data is fixed, and hardcoded in the source.


-- 
DaveA



More information about the Python-list mailing list