查找字符串数学运算符
答
- 使用
for
循环来迭代列表中的项目obj
。 - 使用
if i in x
检查列表obj
中的项目是否存在于字符串x
中。 - 根据步骤2的状态在
result
字典中添加键值。 - 打印结果字典。
例如字符串的
>>> obj = ['<','>','=','<=']
>>> x ='a<=b'
>>> result = {}
>>> for i in obj:
... if i in x:
... result[i]="Present in string."
... else:
... result[i]="Not in string"
...
>>> import pprint
>>> pprint.pprint(result)
{'<': 'Present in string.',
'<=': 'Present in string.',
'=': 'Present in string.',
'>': 'Not in string'}
>>>
更多关于in
和__contains__()
方法: -
>>> "a" in "abcde"
True
>>> "z" in "abcde"
False
>>> "abcde".__contains__("a")
True
>>> "abcde".__contains__("z")
False
答
运营商<=
比<
比<<<
不同有所不同。因此,您需要将构成运算符的多个字符与周围的非运算符字符分开。
在大多数情况下,您可以使用parser来做到这一点。
在简单的情况下,最好的办法是用正则表达式:
tests='''\
a<=b
a<b
a>b
a<<<b
a=b
a==b
a>=b'''
import re
ops=['<','>','=','<=']
pat='([{}]+)'.format(''.join({c for op in ops for c in op}))
for test in tests.splitlines():
m=re.search(pat, test)
if m:
print 'Line: "{}", Operator: "{}", in ops: {}'.format(
test, m.group(0), m.group(0) in ops)
它打印:
Line: "a<=b", Operator "<=", in ops: True
Line: "a<b", Operator "<", in ops: True
Line: "a>b", Operator ">", in ops: True
Line: "a<<<b", Operator "<<<", in ops: False
Line: "a=b", Operator "=", in ops: True
Line: "a==b", Operator "==", in ops: False
Line: "a>=b", Operator ">=", in ops: False
如果你不关心<
从<=
是不同的,你可以测试每个字符串与列表any
:
>>> any(op in 'a<=b' for op in ['<','>','=','<='])
True
但是这并不区分<
和<=
这是不同的运营商。
为什么downvote? – 2015-02-11 19:11:04
现在一切都很有意义,这个问题*完全*值得回答!对不起,请收到我诚挚的歉意,形式为upvote。 – vaultah 2015-02-11 19:13:04
这个讽刺很强。 – HavelTheGreat 2015-02-11 19:13:58