How to check if a string contains only characters from a given set in python

前端 未结 6 925
梦毁少年i
梦毁少年i 2020-12-16 23:07

I have a a user-inputted polynomial and I only want to use it if it only has characters in the string 1234567890^-+x.

How can I check if it does or not

6条回答
  •  鱼传尺愫
    2020-12-17 00:09

    What about just convert both the string into set and checking input_set is subset of good_set as below:

    >>> good_set = set('1234567890^-+x')
    >>> input_set1 = set('xajfb123')
    >>> input_set2 = set('122-32+x')
    >>> input_set1.issubset(good_set)
    False
    >>> input_set2.issubset(good_set)
    True
    >>>
    

提交回复
热议问题