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

后端 未结 7 2067
悲&欢浪女
悲&欢浪女 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:24

    A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:

    input_string = 'abc test'
    input_string_test = input_string
    allowed_list = ['a', 'b', 'c', 'test', ' ']
    
    for allowed_list_item in allowed_list:
        input_string_test = input_string_test.replace(allowed_list_item, '')
    
    if not input_string_test:
        # test passed
    

    So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string.

提交回复
热议问题