2009-04-24 46 views

回答

12

与您的代码的问题是,有再模块中的两个子功能。其中一个是普通表达式,并且有一个与正则表达式对象绑定。您的代码不下列任何一个:

这两种方法是:

re.sub(pattern, repl, string[, count])(docs here)

使用像这样:

>>> y = re.sub(r, 'blue', x) 
>>> y 
'The sky is blue' 

而当你的手之前编译它,你尝试过了,您可以使用:

RegexObject.sub(repl, string[, count=0])(docs here)

使用像这样:

>>> z = r.sub('blue', x) 
>>> z 
'The sky is blue' 
+2

编辑我的答案的方法。 – Unknown 2009-04-24 18:14:20

1

尝试:

x = r.sub("blue", x) 
+1

这是行不通的。然后x就是“蓝色”。 – mike 2009-04-24 17:46:24

+0

当然它不会工作,它是`y = r.sub(x,“蓝色”)` – hasen 2009-04-24 17:59:30

+0

相同的好,我看到他没有捕获返回值,但没有参数的顺序。我已更正我的代码,以正确的顺序包含参数。 – Loktar 2009-04-24 19:24:11

6

你读¶

r.sub(x, "blue") 
# should be 
r.sub("blue", x) 
3

你有API错误

http://docs.python.org/library/re.html#re.sub

pattern.sub(REPL,字符串[,计数])您拨打sub错误方法的理由应该是:

 

import re 
x = "The sky is red" 
r = re.compile ("red") 
y = r.sub("blue", x) 
print x # Prints "The sky is red" 
print y # Prints "The sky is blue" 
 
3

顺便说一句,对于这样一个简单的例子,re模块是矫枉过正:

x= "The sky is red" 
y= x.replace("red", "blue") 
print y