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

Eryk Sun eryksun at gmail.com
Mon Oct 19 14:21:40 EDT 2020


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


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /