正则表达式方法re.sub无法正常工作

时间:2019-04-10 09:03:50

标签: python python-2.7

为什么re.sub在这里不起作用?我试图直接使用它。然后就可以了,但是当包含在一个函数中时,就不起作用了。

msg='I want you'
def replace_pronouns(msg):
    msg = msg.lower()
    print("Before_Replace_msg=",msg)
    if 'me' in msg:
        # Replace 'me' with 'you'
        re.sub('me','you',msg)
    if 'my' in msg:
        # Replace 'my' with 'your'
        re.sub('my','your',msg)
    if 'your' in msg:
        # Replace 'your' with 'my'
        re.sub('your','my',msg)
    if 'i' in msg:
        # Replace 'i' with 'you'
        re.sub('i','you',msg)
    if 'you' in msg:
        # Replace 'you' with 'me'
        print('Entered if Condition')
        re.sub('you','me',msg)
    print("After_Replace_msg1=",msg)

输出:

replace_pronouns(msg)
('Before_Replace_msg=', 'i want you')
Entered if Condition
('After_Replace_msg1=', 'i want you')

我希望收到“您想要我”之类的消息,但它没有改变。

2 个答案:

答案 0 :(得分:0)

re.sub将为Return the string。这需要存储在变量中-原始字符串保持不变。

>>> msg
'I want you'
>>> foo = re.sub('I','you',msg)
>>> foo
'you want you'
>>> msg
'I want you'
>>>
  
    
      

帮助(re.sub):

    
  
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

答案 1 :(得分:0)

每次调用msg时,只需将新值分配给re.sub()。所以上面的函数看起来像这样。

def replace_pronouns(msg):
    msg = msg.lower()
    print("Before_Replace_msg=",msg)
    if 'me' in msg:
        # Replace 'me' with 'you'
        msg = re.sub('me','you',msg)
    if 'my' in msg:
        # Replace 'my' with 'your'
        msg = re.sub('my','your',msg)
    if 'your' in msg:
        # Replace 'your' with 'my'
        msg = re.sub('your','my',msg)
    if 'i' in msg:
        # Replace 'i' with 'you'
        msg = re.sub('i','you',msg)
    if 'you' in msg:
        # Replace 'you' with 'me'
        print('Entered if Condition')
        msg = re.sub('you','me',msg)
    print("After_Replace_msg1=",msg)

作为参考,您可以咨询re.sub()