繁体   English   中英

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

[英]What is wrong with my attempt to do a string replace operation in 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模块中有两个子功能。 一个是普通的,有一个与正则表达式对象相关联。 您的代码不遵循任何一个:

这两种方法是:

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]) (这里的文档)

像这样使用:

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

你读错了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)

你有论据您的来电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

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM