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

2024-05-23 14:28:50 发布

您现在位置: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"

我怎样才能让它印上“天空是蓝色的”?在


Tags: theimportreisblueredprints天空
3条回答

你看错了API

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

在图案.sub(repl,字符串[,count])¶

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

调用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模块中有两个子函数。一个是通用的,还有一个与正则表达式对象相关。您的代码不遵循以下任一项:

这两种方法是:

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)

这样使用:

^{pr2}$

相关问题 更多 >