How to include backslash and quotes in Python strings

前端 未结 4 1050
故里飘歌
故里飘歌 2021-01-27 00:41

I\'ve got an array of special characters that looks something like this.

specialCharList=[\'`\',\'~\',\'!\',\'@\',\'#\',\'$\',\'%\',\'^\',
             \'&\'         


        
相关标签:
4条回答
  • 2021-01-27 01:16

    The backslash \ character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

    example:

    \\  Backslash (\)    
    \'  Single quote (')     
    \"  Double quote (")
    

    Escape characters are documented in the Python Language Reference Manual. If they are new to you, you will find them disconcerting for a while, but you will gradually grow to appreciate their power.

    0 讨论(0)
  • 2021-01-27 01:16

    You can use single, double ot triple quotes for delimiting strings.

    So "'", '"' are ways to have a quote character in your string.

    0 讨论(0)
  • 2021-01-27 01:19

    The readability of your list could be greatly improved by putting your special characters in a string:

    >>> SCL = "`~!@#$%^&*()_-+=|{}[],;:'.><?/" + '"\\'
    >>> specialCharacters = list(SCL)
    

    We're combining two strings, one delimited by " and where we put ', the second delimited by ' and where we put " and \\ (that we have to escape, so we have to put '\\').

    0 讨论(0)
  • 2021-01-27 01:41

    There is an inbuilt module called string in Python. This can be used.

    >>>
    >>> import string
    >>> string.punctuation
    '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
    >>>
    >>> list(string.punctuation)
    ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
    >>>
    
    0 讨论(0)
提交回复
热议问题