3 回答
TA贡献1793条经验 获得超6个赞
假设您的字符串是s:
'$' in s # found
'$' not in s # not found
# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found
对于其他字符,依此类推。
... 要么
pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')
... 要么
chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')
TA贡献1817条经验 获得超14个赞
它应该工作:
('1' in var) and ('2' in var) and ('3' in var) ...
“ 1”,“ 2”等应替换为您要查找的字符。
有关字符串的一些信息,请参阅Python 2.7文档中的此页面,包括有关使用in运算符进行子字符串测试的信息。
更新:这与我上面的建议做的工作相同,重复次数更少:
# When looking for single characters, this checks for any of the characters...
# ...since strings are collections of characters
any(i in '<string>' for i in '123')
# any(i in 'a' for i in '123') -> False
# any(i in 'b3' for i in '123') -> True
# And when looking for subsrings
any(i in '<string>' for i in ('11','22','33'))
# any(i in 'hello' for i in ('18','36','613')) -> False
# any(i in '613 mitzvahs' for i in ('18','36','613')) ->True
TA贡献1873条经验 获得超9个赞
import timeit
def func1():
phrase = 'Lucky Dog'
return any(i in 'LD' for i in phrase)
def func2():
phrase = 'Lucky Dog'
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
func1_time = timeit.timeit(func1, number=100000)
func2_time = timeit.timeit(func2, number=100000)
print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))
输出:
Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371
因此,任何代码都更紧凑,而条件代码则更快。
添加回答
举报