1

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

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

The problem is, I want to include the ' and the \ characters but can't because they're used for strings and escaping. How would I go about including these characters?

John Coleman
  • 51,337
  • 7
  • 54
  • 119
user1675111
  • 8,695
  • 4
  • 18
  • 14

4 Answers4

12

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
avasal
  • 14,350
  • 4
  • 31
  • 47
  • 1
    It is also nice to know that python doesn't have any special meaning for single and double quotes. So the string `"'"` is equivalent to `'\''` except that the former is easier to read (in my opinion). – mgilson Sep 25 '12 at 05:05
3

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

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

Python's "triple quotes" are either three double-quotes in a row, or three single-quotes in a row. However, e.g. ''''''' does not work to surround a single quote in triple-single quotes - it will be seen as an empty string in triple-single quotes, and then an unmatched single quote. We can, however, use '''"''' or """'""" (although there is not much of a point in this case).

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
sureshvv
  • 4,234
  • 1
  • 26
  • 32
1

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 '\\').

Pierre GM
  • 19,809
  • 3
  • 56
  • 67
0

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

>>>
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>>
>>> list(string.punctuation)
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
>>>
kvivek
  • 3,321
  • 1
  • 15
  • 17