我在这里做错了什么?我试图在Python中进行字符串替换操作有什么问题?
import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
如何让它打印“天空是蓝色的”?
我在这里做错了什么?我试图在Python中进行字符串替换操作有什么问题?
import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
如何让它打印“天空是蓝色的”?
与您的代码的问题是,有再模块中的两个子功能。其中一个是普通表达式,并且有一个与正则表达式对象绑定。您的代码不下列任何一个:
这两种方法是:
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'
你读¶
r.sub(x, "blue")
# should be
r.sub("blue", x)
你有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"
顺便说一句,对于这样一个简单的例子,re
模块是矫枉过正:
x= "The sky is red"
y= x.replace("red", "blue")
print y
编辑我的答案的方法。 – Unknown 2009-04-24 18:14:20