String contains any character in group?

后端 未结 4 1087
不思量自难忘°
不思量自难忘° 2020-12-10 16:05

I have a set of characters: \\,/,?,% etc. I also have a string, lets say \"This is my string % my string ?\"

I want to check if any of the characters are present in

相关标签:
4条回答
  • 2020-12-10 16:12

    You could use any here.

    >>> string = r"/\?%"
    >>> test = "This is my string % my string ?"
    >>> any(elem in test for elem in string)
    True
    >>> test2 = "Just a test string"
    >>> any(elem in test2 for elem in string)
    False
    
    0 讨论(0)
  • 2020-12-10 16:17
    In [1]: import re
    In [2]: RE = re.compile('[\\\/\?%]')
    In [3]: RE.search('abc')
    
    In [4]: RE.search('abc?')
    Out[4]: <_sre.SRE_Match at 0x1081bc1d0>
    In [5]: RE.search('\\/asd')
    Out[5]: <_sre.SRE_Match at 0x1081bc3d8>
    

    None indicates non characters in the set are present in the target string.

    0 讨论(0)
  • 2020-12-10 16:25

    I think Sukrit probably gave the most pythonic answer. But you can also solve this with set operations:

    >>> test_characters = frozenset(r"/\?%")
    >>> test = "This is my string % my string ?"
    >>> bool(set(test) & test_characters)
    True
    >>> test2 = "Just a test string"
    >>> bool(set(test2) & test_characters)
    False
    
    0 讨论(0)
  • 2020-12-10 16:33

    Use regex!

    import re
    
    def check_existence(text):
        return bool(re.search(r'[\\/?%]', text))
    
    text1 = "This is my string % my string ?"
    text2 = "This is my string my string"
    
    print check_existence(text1)
    print check_existence(text2)
    
    0 讨论(0)
提交回复
热议问题