Python 3.6:' elif'语句破坏了单词交换功能

时间:2018-05-16 16:34:00

标签: python string python-3.x

如果在提供的字符串中找不到参数b或c,我试图让程序返回print语句。但是当我添加它时,它看起来像这样:

Not in string: dylan
Not in string: dylan
Not in string: dylan
BOB  DYLAN  .
Not in string: BOB
Not in string: BOB
Not in string: BOB
BOB  DYLAN  .
Not in string: dylan
Not in string: dylan
Not in string: dylan
 DYLAN  .
Not in string: DYLAN
Not in string: DYLAN
Not in string: DYLAN
BOB   .

然而,取出2个elif语句,得到了我想要的输出的一半:

BOB and DYLAN work together. # good
BOB and DYLAN work together. #good
Not in string: "dylan" #desired output
Not in string: "BoB" #desired ouput

以下是我所做的功能:

import re

def swapfunc(a,b,c):
    def func(m):
        g = m.group(1).lower()
        if g == c.lower():
            return b.upper()
        elif g == b.lower():
            return c.upper()
        #elif b not in a: # Adding these 2 elif's screw up the function entirely
            #return print("Not in string:" , b)
        #elif c not in a:
            #return print("Not in string:" , c)        
        else:
            return m.group(1)

    return re.sub("(\w+)",func,a)

print(swapfunc("Dylan and Bob work together.", "dylan", "bob")) # this is good
print(swapfunc("Dylan and Bob work together.", "BOB", "DylAn")) #this is good     
print(swapfunc("and Bob work together.", "dylan", "bob"))
# Not in string: "dylan" <-- should be the output
print(swapfunc("Dylan and work together.", "DYLAN", "BoB"))
# Not in string: "BoB"  <-- should be the output

2 个答案:

答案 0 :(得分:3)

由于您通过elif致电fun,因此re.sub('(\w+)')测试会分别应用于每个单词

所以不,dylan不在您的句子中,但是对每个单词执行此测试,单独。字符串"and Bob work together."中有4个单独的单词,因此您测试4次,并打印4次。此外,由于您在这些情况下返回Noneprint()函数的结果),因此您告诉re.sub()完全删除匹配的字词。

在使用re.sub()之前,您需要先单独运行

if b not in a:
    print("Not in string:", b)
    return

if c not in a:
    print("Not in string:", c)
    return

return re.sub("(\w+)", func, a)

答案 1 :(得分:1)

以下是我的建议

import re

def swapfunc(text, b, c):
    if re.search(r"\b"+b+r"\b|\b"+c+r"\b", text, re.I):

        if not re.search(r"\b"+b+r"\b", text, re.I):
            return b+" not found";
        elif not re.search(r"\b"+c+r"\b", text, re.I):
            return c+" not found";
        else:
            text = re.sub(r"\b"+b+r"\b", '__c__', text, flags=re.IGNORECASE)
            text = re.sub(r"\b"+c+r"\b", '__b__', text, flags=re.IGNORECASE)
            text = text.replace('__c__', c.upper())
            text = text.replace('__b__', b.upper())
            return text
    else:
        return "Values "+b+" and "+c+" not found";

print(swapfunc("dylan and Bob work together.", "Dylan", "bob"))
print(swapfunc("Dylan and Bob work together.", "BOB", "DylAn"))
print(swapfunc("and Bob work together.", "dylan", "bob"))
print(swapfunc("Dylan and work together.", "DYLAN", "BoB"))