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



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

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

您的elif测试将分别应用于每个单词,因为您通过re.sub('(w+)')调用fun

所以不,dylan不在你的句子中,但这个测试是针对每个单词分别执行的。字符串中有 4 个单独的单词"and Bob work together.",因此您测试 4 次,打印 4 次。此外,由于在这些情况下返回None(print()函数的结果),因此您告诉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)

以下是我的建议

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"))

最新更新