How do I verify that a string only contains letters, numbers, underscores and dashes?

前端 未结 11 965
小鲜肉
小鲜肉 2020-11-29 18:51

I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.

11条回答
  •  日久生厌
    2020-11-29 19:19

    As an alternative to using regex you could do it in Sets:

    from sets import Set
    
    allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
    
    if Set(my_little_sting).issubset(allowed_chars):
        # your action
        print True
    

提交回复
热议问题