codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Simple question - end a raw string with a single backslash ?


On 10/19/20, Grant Edwards <grant.b.edwards at gmail.com> wrote:
> On 2020-10-19, Stephen Tucker <stephen_tucker at sil.org> wrote:
>
>> For a neatish way to get a string to end with a single backslash, how
>> about
>>    mystr = r"abc\ "[:-1]
>> (Note the space at the end of the rough-quoted string.)
>
> That's the first thing I thought of, though I would probably use a
> non-space character to avoid convusion when reading:
>
>    mystr = r'abc\_'[:-1]

But it doesn't actually "end a raw string with a single backslash".
The compiler could be optimized for slicing string literals, but it's
not. For example:

    >>> dis.dis(r"r'spam\eggs\_'[:-1]")
      1           0 LOAD_CONST               0 ('spam\\eggs\\_')
                  2 LOAD_CONST               1 (None)
                  4 LOAD_CONST               2 (-1)
                  6 BUILD_SLICE              2
                  8 BINARY_SUBSCR
                 10 RETURN_VALUE

For comparison:

    >>> dis.dis(r"r'spam\eggs' '\\'")
      1           0 LOAD_CONST               0 ('spam\\eggs\\')
                  2 RETURN_VALUE