Does the string contain any character in the group?

I have a character set: \, /,?,%, Etc. I also have a string, you can say: "Is this my string% is my string?"

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

This is not a substring check, but a character check in a set.

I could do this:

my_str.find( "/" ) or my_str.find( "\\" ) or my_str.find( "?" )

but he is very ugly and inefficient.

Is there a better way?

+4
source share
4 answers

Here you can use any.

>>> 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
+9
source

I think that Sucritus probably gave the most pythonic answer. But you can also solve this with the given 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
+3
source
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 , .

+1

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)
+1

All Articles