Why can't Python's raw string literals end with a single backslash?

后端 未结 12 1373
后悔当初
后悔当初 2020-11-22 07:37

Technically, any odd number of backslashes, as described in the documentation.

>>> r\'\\\'
  File \"\", line 1
    r\'\\\'
       ^
Syn         


        
12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 08:17

    That's the way it is! I see it as one of those small defects in python!

    I don't think there's a good reason for it, but it's definitely not parsing; it's really easy to parse raw strings with \ as a last character.

    The catch is, if you allow \ to be the last character in a raw string then you won't be able to put " inside a raw string. It seems python went with allowing " instead of allowing \ as the last character.

    However, this shouldn't cause any trouble.

    If you're worried about not being able to easily write windows folder pathes such as c:\mypath\ then worry not, for, you can represent them as r"C:\mypath", and, if you need to append a subdirectory name, don't do it with string concatenation, for it's not the right way to do it anyway! use os.path.join

    >>> import os
    >>> os.path.join(r"C:\mypath", "subfolder")
    'C:\\mypath\\subfolder'
    

提交回复
热议问题