【问题标题】:Check if any character in a string is not in another string [duplicate]检查字符串中的任何字符是否不在另一个字符串中[重复]
【发布时间】:2019-11-11 03:29:56
【问题描述】:

我有一个函数,用户输入字符串s
如果s 中的任何字符不在"0123456789e+-. " 中,则该函数应返回False

我试过了:

if any(s) not in "0123456789e+-. ":
    return False

这个:

if any(s not in "0123456789e+-. "):
    return False

还有这个:

if any(character for character in s not in "0123456789e+-. "):
    return False

在这种情况下我应该如何使用any()函数?

【问题讨论】:

  • if any(character not in "0123456789e+-. " for character in s ):

标签: python python-3.x string iterator any


【解决方案1】:

您想遍历s 中的每个字符并检查它是否不在集合"0123456789e+-. "

chars = set("0123456789e+-. ")
if any(c not in chars for c in s):
    return False

在这种情况下,您也可以使用all 来检查相同的情况

chars = set("0123456789e+-. ")
if not all(c in chars for c in s):
    return False

【讨论】:

  • 怎么样:return all(c in set("0123456789e+-. ") for c in s)
  • 这是一个很好的观点@Austin,但我不知道 OP 是否想在另一种情况下返回 True,因此我没有添加它
  • 这将在每次迭代时创建一个新集合,不是吗?没什么大不了的,但只是其中之一。
  • 公平点@MadPhysicist 相应更新!
【解决方案2】:

只是与sets 不同:

pattern = "0123456789e+-. "
user_input = '=-a'

if set(user_input) - set(pattern):
    return False

或者只测试负子集:

if not set(user_input) < set(pattern):
    return False

https://docs.python.org/3.7/library/stdtypes.html#set-types-set-frozenset

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    相关资源
    最近更新 更多