Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String contains any character in group?

Tags:

python

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 the string.

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

I could do this:

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

but it's very ugly and inefficient.

Is there a better way?

like image 791
Igor Avatar asked Oct 19 '13 07:10

Igor


3 Answers

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
like image 77
Sukrit Kalra Avatar answered Oct 18 '22 16:10

Sukrit Kalra


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
like image 8
Kevin Stone Avatar answered Oct 18 '22 18:10

Kevin Stone


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)
like image 3
lancif Avatar answered Oct 18 '22 17:10

lancif