用反向搜索和替换字符串

时间:2014-01-16 12:58:13

标签: python regex

我正在尝试在字符串中查找单词并以反向形式替换它们。 所以,当我This 17时,我想推出sihT 17

但我不知道如何在re.sub()

中反转字符串本身
import re

pat_word = re.compile("[a-zA-Z]+")
input = raw_input ("Input: ")

match = pat_word.findall(input)
if match: 
    s = re.sub(pat_word, "reverse", input)
    print s

1 个答案:

答案 0 :(得分:2)

您可以使用re.sub内的功能:

s = re.sub(pat_word, lambda m:m.group(0)[::-1], input)

或者简单地说:

s = pat_word.sub(lambda m:m.group(0)[::-1], input)

来自help(re.sub)

  

sub(pattern,repl,string,count = 0,flags = 0)

     

返回通过替换最左边获得的字符串    由字符串中的模式非重叠出现    替换代表 repl可以是字符串也可以是可调用的;    如果处理了一个字符串,则反斜杠转义。如果是    一个可调用的,它传递了匹配对象,必须返回    要使用的替换字符串。

请注意input是Python中的内置函数,因此不要将其用作变量名。

相关问题