簡體   English   中英

如何將輸入的一部分作為變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM