作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何将\、/、:、*、?、"、<、>、| 等符号放入列表中?
如果我这样做:
illegalchar = ['\', '/' ,':' ,'*', '?', '"', '<', '>', '|']
分隔项目的逗号将被视为包含 ]
PS:是检查文件名是否包含非法字符(不能做成文件),如果有其他方法请告诉我,谢谢!
最佳答案
使用原始字符串(通过在字符串前面放置一个 r
来表示)。然后,将原始字符串转换为列表:
illegals = [i for i in r'\/:*?"<>|']
# OR, using @abccd's suggestion, just use list()
illegals = list(r'\/:*?"<>|')
illegals
# ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
请注意 '\\'
在打印时仍然是单个反斜杠,但在值中第一个反斜杠存储为转义字符。
您可以在 documentation of lexical analysis. 上阅读更多内容
这回答了问题,但实际上您将 string
视为字符的 list
,因此以下两个将返回相同的元素:
[i for i in list(r'\/:*?"<>|')]
[c for c in r'\/:*?"<>|']
至于如何识别一个文件名是否有这些字符,你可以这样做:
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
这只是众多方法中的一种。您甚至可以选择正则表达式方法:
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
关于python - 如何将符号放入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759429/
我是一名优秀的程序员,十分优秀!