我尝试在Python中执行字符串替换操作有什么问题?

mik*_*ike 2 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"
Run Code Online (Sandbox Code Playgroud)

如何打印"天空是蓝色的"?

Pao*_*ino 12

代码的问题在于re模块中有两个子功能.一个是普通的,有一个与正则表达式对象相关联.您的代码不遵循任何一个:

这两种方法是:

re.sub(pattern, repl, string[, count]) (这里的文档)

像这样使用:

>>> y = re.sub(r, 'blue', x)
>>> y
'The sky is blue'
Run Code Online (Sandbox Code Playgroud)

当你手动编译它时,你可以尝试使用:

RegexObject.sub(repl, string[, count=0]) (这里的文档)

像这样使用:

>>> z = r.sub('blue', x)
>>> z
'The sky is blue'
Run Code Online (Sandbox Code Playgroud)


Unk*_*own 6

你读错了API

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

pattern.sub(repl,string [,count])

r.sub(x, "blue")
# should be
r.sub("blue", x)
Run Code Online (Sandbox Code Playgroud)