[英]if there is str('a') or str('b') or str('c') in a user input then do something
I would like to put multiple strings for one in statement one one line: 我想放多串为一个在声明中一一行:
input = str(raw_input(''))
if str('a') or ('b') or ('c') in str(input):
print "a string"
else:
print "no"
Is it possible to have multiple strings for a single in statement? 一个in语句可以有多个字符串吗?
First of all str('a') == 'a'
(because 'a'
is already a string), so you can leave that out. 首先str('a') == 'a'
(因为'a'
已经是一个字符串),因此可以将其省略。
'a' or 'b' or 'c' in input
This expression is parsed as the following: 该表达式解析如下:
('a') or ('b') or ('c' in input)
So you are checking if 'a'
or 'b'
evalute to true, which is the case. 因此,您正在检查'a'
或'b'
评估结果是否为true。 If you want to check them all using the in
operator, you have to explicitely specify that: 如果要使用in
运算符检查它们,则必须明确指定:
'a' in input or 'b' in input or 'c' in input
You can also simplify that then: 您还可以简化以下操作:
any(x in input for x in ('a', 'b', 'c'))
It is, but what you wrote does something entirely different. 是的,但是您写的内容完全不同。 It checks to see if str('a')
is truthy, if 'b'
is truthy, or if 'c'
is in input
. 它检查str('a')
是否真实, 'b'
是否真实,或者input
是否包含'c'
。 While Python is very readable, it doesn't make assumptions about what you write. 尽管Python具有很高的可读性,但它不会对您编写的内容进行任何假设。 You have to be explicit: 您必须明确:
if 'a' in input or 'b' in input or 'c' in input:
...
Or: 要么:
strings = ('a', 'b', 'c')
if any(s in input for s in strings):
...
Calling str()
with a string argument is pointless. 用字符串参数调用str()
是没有意义的。 Also, input
is the name of a builtin, so I suggest you rename your variable. 另外, input
是内置名称,因此建议您重命名变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.