TAGS :Viewed: 5 - Published at: a few seconds ago

[ How to include backslash and quotes in Python strings ]

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


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?

Answer 1

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


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

Answer 2

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

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

Answer 3

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