我正在尝试验证my字符串是否仅包含以下值:'\n‘、'.’和'o‘。它们不需要都在那里,但如果包含这些字符之外的任何内容,我的函数应该返回false。
我有一个包含这些字符的字符串,但它也包含'0‘。但是,使用我的函数,这将返回到true。
I am primarily having issues with the first line, all others work as expected. I am not able to use regex so an alternative would be greatly appreciated!发布于 2019-10-18 02:36:52
使用all函数:
if all (char in ".o\n" for char in s):如果您愿意,可以创建一个字符列表,而不是字符串:
if all (char in ['.', 'o', '\n'] for char in s):发布于 2019-10-18 02:36:58
您可以使用set来执行以下操作:
if s and set(s) - set('\n.o'):
return False
# s consists entirely of \n, o and .我不清楚如果s为空会发生什么。上面的代码将允许它;如果您希望拒绝它,请将第一行改为
if set(s) - set('\n.o'):发布于 2019-10-18 02:41:46
这是另一种你可以做到的方法:
allowed_chars = ['\n', '.', 'o']
your_string = '\n.o'
all([False for i in set(your_string) if i not in allowed_chars])返回True。
your_string = '\n.ogg'返回False。
https://stackoverflow.com/questions/58438776
复制相似问题