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)
{'~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/'}
>>>
Answer from user2555451 on Stack OverflowYou 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)
{'~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/'}
>>>
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:
- Wraps the string in three quotes to simplify handling the single or double quote issue
- Puts an
rin front of the string to handle the escape character setconverts 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)
{']'}
Videos
Please advise to complete the code if special characters in username print username not allowed, i am using replit for school if this helps.
special=('!','@','#','$','%','^','&','*','(',')','-','_','+','=','')
if special in Username:
print('username is incorrect')
The standard string module provides string.punctuation, which contains punctuation characters. You can test for membership in that:
def ispunct(ch):
return ch in string.punctuation
There's no built-in function, but you can always build one.
This function checks user input for illegal characters (for naming files in Windows), cuts them out, notifies user and asks whether to submit a corrected string.
def infinite_char_check(string):
"""
Check string against exclusion list, correct and ask to submit.
Parameters
----------
string : str
Returns
-------
string : str
"""
punctuation = ["|", "/", "\\", ":", "*", "?", '"', "<", ">"]
the_same = string
for symb in punctuation:
string = string.replace(symb, "")
if string != the_same:
print()
print(
"Illegal characters detected! "
'Please avoid using this set: /,\\,:,*,?,",<,>,|'
)
print("Corrected string: ", string)
print(
'Input "Y" (or "y") if you\'d like to change it, '
"otherwise input any string"
)
spchk = input()
if spchk in ("y", "Y"):
print("Input experiment name")
new_name = input()
string = infinite_char_check(new_name)
return string