字符串包含组中的任何字符?

Igo*_*gor 8 python

我有一组字符:\,/,?,%等.我也有一个字符串,让我们说"这是我的字符串%my string?"

我想检查字符串中是否存在任何字符.

这不是检查子字符串,而是检查集合中的字符.

我能做到这一点:

my_str.find( "/" ) or my_str.find( "\\" ) or my_str.find( "?" )
Run Code Online (Sandbox Code Playgroud)

但它非常丑陋且效率低下.

有没有更好的办法?

Suk*_*lra 12

你可以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
Run Code Online (Sandbox Code Playgroud)


Kev*_*one 6

我认为 Sukrit 可能给出了最pythonic 的答案。但是你也可以通过集合操作来解决这个问题:

>>> 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
Run Code Online (Sandbox Code Playgroud)


lan*_*cif 5

使用正则表达式!

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)
Run Code Online (Sandbox Code Playgroud)