In Python, how to check if a string only contains certain characters?

后端 未结 7 2075
悲&欢浪女
悲&欢浪女 2020-12-02 12:36

In Python, how to check if a string only contains certain characters?

I need to check a string containing only a..z, 0..9, and . (period) and no other character.

7条回答
  •  一向
    一向 (楼主)
    2020-12-02 13:30

    Simpler approach? A little more Pythonic?

    >>> ok = "0123456789abcdef"
    >>> all(c in ok for c in "123456abc")
    True
    >>> all(c in ok for c in "hello world")
    False
    

    It certainly isn't the most efficient, but it's sure readable.

提交回复
热议问题