Special Characters in string literals

Question:

I am making a set in Python to house all the symbols on my keyboard, but obviously a few pose some issues. Is there a way to get them all in there without encountering problems?

Here is my set:

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

To get around commenting out most of it, since in Python # is to comment, I enclosed everything like so:

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

Which works for that character, but now I can already see an issue when I come across the ' and . Is there a better way to make this set?

Asked By: Illyduss

||

Answers:

You can fix the backslash by escaping it and ' can be fixed by putting it in double quotes:

symbols = {..., '\', ... "'", ...}

But typing all this out is pretty tedious. Why not just use string.punctuation instead:

>>> from string import punctuation
>>> set(punctuation)
{'~', ':', "'", '+', '[', '\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/'}
>>>
Answered By: user2555451

I would rather put them all in triple quotes, like this. It would ignore any special characters:

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

user2555451’s answer is spot on, but just as an observation on how to get these into Python efficiently – the first part of your question – try this:

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

That:

  1. Wraps the string in three quotes to simplify handling the single or double quote issue
  2. Puts an r in front of the string to handle the escape character
  3. set converts the string to a set

The initial string was missing the close square bracket, just as an aside. Using a simple set operator:

>>> symbols - set(string.punctuation)
{']'}
Answered By: angus l

Just use a "\" which outputs "" in the python terminal, if you try to use "" then python will throw you an error so, instead of "" use "\" which will print the same value that is: "".

Answered By: Abdul Kaif
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.