2017-03-27 75 views
2

所以我用遞歸工作,如何使用遞歸選擇字符串中的特定部分?

的問題是:到目前爲止"(43)"

我的代碼:

" Good(43) Morning"

我必須用遞歸來打印所有的信息在括號內是這樣是:

def extractor(myString): 
    if len(myString) == 0: 
     return "" 



    if myString[0] == "(": 
     return myString[0] 
    if myString[0] == ")": 
     return myString[:] 
    else: 
     return extractor(myString[1:]) 

我只能得到括號。我怎麼能改變它?

回答

1

就快:

def extractor(myString): 
    if not myString: # empty strings are falsy 
     return "" 
    if myString[0] == "(": 
     if myString[-1] == ")": # success 
      return myString 
     else: # only starts with (, trim from the end 
      return extractor(myString[:-1]) 
    else: # doesn't start with (, trim from beginning 
     return extractor(myString[1:]) 
+0

這是工作,但我不能在函數中使用任何構建除LEN() –

+0

'str.startswith'和'STR .endswith'是方法,而不是函數,但足夠公平,我會改變它。 – L3viathan

+0

非常感謝你 –

0

如果你有興趣,這裏是你的代碼的迭代版本。 :)

def iterative_extractor(mystring): 
    if not mystring: 
     return "" 

    while mystring[0] != "(" or mystring[-1] != ")": 
     if mystring[0] != "(": 
      mystring = mystring[1:] 
     else: 
      mystring = mystring[:-1] 
    return mystring 

OR:

def iterative_extractor(mystring): 
    if not mystring: 
     return "" 

    while mystring[0] != "(": 
     mystring = mystring[1:] 

    while mystring[-1] != ")": 
     mystring = mystring[:-1] 

    return mystring 

輸出:

mystring = "Lol (234) mate!" 
print(iterative_extractor(mystring)) 
>>> "(234)" 
相關問題