How to print a single backslash?

后端 未结 4 862
别跟我提以往
别跟我提以往 2020-11-22 01:43

When I write print(\'\\\') or print(\"\\\") or print(\"\'\\\'\"), Python doesn\'t print the backslash \\ symbol. Instead

相关标签:
4条回答
  • 2020-11-22 02:12

    You need to escape your backslash by preceding it with, yes, another backslash:

    print("\\")
    

    And for versions prior to Python 3:

    print "\\"
    

    The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

    As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

    See the Python 3 documentation for string literals.

    0 讨论(0)
  • 2020-11-22 02:17

    A backslash needs to be escaped with another backslash.

    print('\\')
    
    0 讨论(0)
  • 2020-11-22 02:21

    you should escape it...with \

    print('\\')
    
    0 讨论(0)
  • 2020-11-22 02:26

    A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

    >>> print(chr(92))
    \
    
    0 讨论(0)
提交回复
热议问题