[英]How do I take part of an input as a variable?
大家好,我是Stackoverflow。 在学习Python的过程中,我将创建一个基本的Ubuntu终端模拟器作为一个小项目。
我需要输入的一部分并将其转换为变量,因此可以将其添加到“命令输出”中。 示例:如果有人放置“ sudo add-apt-repository ppa:webupd8team / tor-browser”,则该代码将能够提取“ webupd8team”,并将其用作输出的一部分,然后提取tor-browser,然后将其用作输出的一部分。
我已经有一些if / else过滤器来检查某些命令(例如,Sudo),但是对于某些事情,我无法真正通过每个可能的选项。
if "sudo" in originalInput: #Checks to see if "sudo" is in the command input.
password = input("[sudo] enter password for evan:") #Creating another input if sudo is found in input1
if password == "1qaz2wsx":
if "cd" in originalInput:
print("This is here for testing purposes") #Haven't started working on the CD command yet
CommandPrompt()
if "add-apt-repository ppa:" in originalInput:
confirm = input("You are about to add this PPA to your system. Confirm?")
if confirm == "1": #Just here to pressing enter will activate ppa_install(), function made to mimic PPA installation
return True
else:
ppa_install()
CommandPrompt()
我已经为PPA命令设置了这个东西,但是我需要能够使代码在sudo / add-apt / whatever之后拉东西并在输出中使用它们。
看来您需要使用split方法(该方法将在给定的定界符(默认为空格)处分割字符串)或regex软件包。
在这种情况下,一种快速,低技术的方法是在空格上分割字符串并拉出“ ppa:webupd8team / tor-browser”。 用冒号和斜线除以您选择的任何字符串处理方式(查找,索引,字符串切片),即可得到所需的字符串。
有关详细信息,请参见文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.