如何使用递归选择字符串中的特定部分?

时间:2017-03-27 22:10:59

标签: python recursion

所以我正在使用递归,

问题是:

" Good(43) Morning"

我必须使用递归来打印括号内的所有信息,如下所示:"(43)"

到目前为止我的代码是:

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



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

我只能得到括号。我怎么能改变它?

2 个答案:

答案 0 :(得分: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:])

答案 1 :(得分: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)"