我有一組字符:\,/,?,%等 我也有一個字符串,可以說「這是我的字符串%我的字符串?」字符串包含組中的任何字符?
我想檢查字符串中是否存在任何字符。
這不是檢查子字符串,而是檢查集合中的字符。
我可以這樣做:
my_str.find("/") or my_str.find("\\") or my_str.find("?")
但它是非常醜陋和低效。
有沒有更好的方法?
我有一組字符:\,/,?,%等 我也有一個字符串,可以說「這是我的字符串%我的字符串?」字符串包含組中的任何字符?
我想檢查字符串中是否存在任何字符。
這不是檢查子字符串,而是檢查集合中的字符。
我可以這樣做:
my_str.find("/") or my_str.find("\\") or my_str.find("?")
但它是非常醜陋和低效。
有沒有更好的方法?
您可以在這裏使用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
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
表示在組非字符存在於目標串。
我認爲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
在邏輯上下文中,例如'if'語句,'bool()'調用是不必要的。即'如果設置(test2)&test_characters:'。 'test_characters'也不需要被凍結。 – martineau
使用正則表達式!
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)
獲取錯誤。這是我的字符串:invalid_chars =「/ \\?%*:|」<> \。 「並且錯誤是」行後續字符出現意外字符「。使用此處的設置:http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words – Igor
字符串格式錯誤。使用'r'/ \ ?%*:|「<>。 「'。我相信它擁有你想要的所有角色。 –