1

I have a function where the user inputs the string s.
If any character in s is not in "0123456789e+-. ", the function should return False.

I tried this:

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

This:

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

And This:

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

How should I use the any() function in this case?

2 Answers2

3

You want to iterate over every character in s and check if it is not in the set "0123456789e+-. "

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

You can also use all in this case to check for the same condition

chars = set("0123456789e+-. ")
if not all(c in chars for c in s):
    return False
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
3

Just with sets difference:

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

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

or just test for negative subset:

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

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

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105