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

前端 未结 6 927
梦毁少年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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 23:48

    Yet another way to do it, now using string.translate():

    >>> import string
    >>> all_chars = string.maketrans('', '')
    >>> has_only = lambda s, valid_chars: not s.translate(all_chars, valid_chars)
    >>> has_only("abc", "1234567890^-+x.")
    False
    >>> has_only("x^2", "1234567890^-+x.")
    True
    

    It is not the most readable way. It should be one of the fastest if you need it.

提交回复
热议问题