Test if string ONLY contains given characters

前端 未结 7 531
甜味超标
甜味超标 2021-01-12 13:19

What\'s the easiest way to check if a string only contains certain specified characters in Python? (Without using RegEx or anything, of course)

Specifically, I have

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 13:52

    Assuming the discrepancy in your example is a typo, then this should work:

    my_list = ['aba', 'acba', 'caz']
    result = [s for s in my_list if not s.strip('abc')]
    

    results in ['aba', 'acba']. string.strip(characters) will return an empty string if the string to be stripped contains nothing but characters in the input. Order of the characters should not matter.

提交回复
热议问题