如何使用 Python 2 检查字符串中是否包含多个特定字符?
例如,给定以下字符串:
The criminals stole $1,000,000 in jewels.
如何检测它是否包含美元符号 ("$")、逗号 (",") 和数字?
最佳答案
假设你的字符串是 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')
[编辑:在 s 答案中添加了 '$']
https://stackoverflow.com/questions/5188792/