gpt4 book ai didi

python - 如何将符号放入列表

转载 作者:行者123 更新时间:2023-11-28 22:20:43 25 4
gpt4 key购买 nike

如何将\、/、:、*、?、"、<、>、| 等符号放入列表中?

如果我这样做:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com