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

前端 未结 6 928
梦毁少年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-16 23:51

    Use a regular expression:

    import re
    
    if re.match('^[-0-9^+x]*$', text):
        # Valid input
    

    The re module comes with Python 2.5, and is your fastest option.

    Demo:

    >>> re.match('^[-0-9^+x]*$', '1x2^4-2')
    <_sre.SRE_Match object at 0x10f0b6780>
    

提交回复
热议问题