Use raw strings (denoted by putting an r
in front of your strings). Then, transform your raw string into list:
illegals = [i for i in r'\/:*?"<>|']
# OR, using @abccd's suggestion, just use list()
illegals = list(r'\/:*?"<>|')
illegals
# ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
Note the '\\'
when printed is still a single backslash, but in value the first backslash is stored as an escape character.
You can read more on the documentation of lexical analysis.
This answers the question, but in reality you a string
is treated like a list
of characters, so both of the following will return the same elements:
[i for i in list(r'\/:*?"<>|')]
[c for c in r'\/:*?"<>|']
As for how to identify if a filename has any of these characters, you can do this:
valid_file = 'valid_script.py'
invalid_file = 'invalid?script.py'
validate = lambda f: not any(c for c in r'\/:*?"<>|' if c in f)
validate(valid_file)
# True
validate(invalid_file)
# False
This is just one of the many ways. You might even opt for a regex approach:
import re
# Note in regex you still need to escape the slash and backslash in the match group
validate = lambda f: not re.search(r'[\\\/:*?\"<>|]+', f)
validate(valid_file)
# True
validate(invalid_file)
# False