[英]How could I make an input if/else check if something is PART of an input?
Ok, Im new to Python, as in only been coding in it for ~2.5 weeks. 好的, 我是Python的新手,因为只用它编写了约2.5周的代码。 Please remember that in your answers.
请记住您的答案。 :D.
:D
Im currently trying to make a program, as actually MAKING programs with stuff Iv been learning online helps me to learn it (Extremely basic Ubuntu terminal emulator, why not ;p) and I need to make an input that checks if something in an if/else statement is in the input. 我目前正在尝试制作一个程序,因为实际上在网上学习一些东西并制作了一些东西可以帮助我学习(极其基本的Ubuntu终端模拟器,为什么不; p),我需要输入一个输入来检查if /其他语句在输入中。
Example: 例:
input1 = input("test@ubuntu:~$")
if input1 == "sudo":
input2 = input("[sudo] enter password for test:")
But have the if statement trigger if sudo/cd/anything is mentioned ANYWHERE in the input. 但是,如果在输入中任何地方提到sudo / cd / anything,都有if语句触发。 If someone put in "sudo cd / " it would trigger because the input has Sudo in it.
如果有人输入“ sudo cd /”,它将触发,因为输入中包含Sudo。 Again, Im new to this language as a whole, so please no "duh, you just do this, you should have known that" answers please!
再说一次,我是整体上对这种语言不熟悉的人,所以请不要回答“ du,您只要这样做,就应该知道”,请回答!
if "sudo" in input1:
...
This checks substring inclusion as well as appearance in a sequence (list, tuple, string, etc.). 这将检查子字符串的包含以及序列(列表,元组,字符串等)中的外观。
For more general use, to find if any disallowed term is in the input: 对于更一般的用途,要查找输入中是否有任何不允许的术语:
bad_list = [
"sudo",
"cd",
"/",
"anything"
]
if any([word in input for word in bad_list]):
The any (logical or) and all (logical and) operators go through a list of values, taking them as Booleans (checking the "truthy" property of each element). 任何 (逻辑或)运算符和所有 (逻辑和)运算符都会经过一个值列表,并将它们视为布尔值(检查每个元素的“真实”属性)。 The stuff in brackets is called a "list comprehension", and it's a way of building a list by description -- sort of coding a for loop inside a list.
方括号中的内容称为“列表理解”,这是一种通过描述构建列表的方式-一种在列表内部编码for循环的方式。
@Prune's answer is what you asked for. @Prune的答案就是您的要求。 But for what you want to do, I believe
.starstwith('sudo')
could be helpful. 但是对于您想做的事情,我相信
.starstwith('sudo')
可能会有所帮助。
if input1.strip().starstwith('sudo'):
...
Because otherwise, if you run something like echo 'sudo'
for example, it'll ask you the password. 因为否则,例如,如果您运行类似
echo 'sudo'
的操作,它将询问您密码。
Note: the .strip
removes any spaces/line break at the beginning or at the end of the string 注意:
.strip
删除字符串开头或结尾的所有空格/换行符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.