tags:

views:

247

answers:

5

What am I doing wrong here?

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"

How do i get it to print "The sky is blue"?

+1  A: 

Try:

x = r.sub("blue", x)
Loktar
That doesn't work. Then x is just "blue".
mike
of course it wont work, it's the same as `y = r.sub(x, "blue")`
hasen j
Good catch, I saw that he wasn't capturing the return value but not the order of parameters. I've corrected my code to have the params in the right order.
Loktar
+10  A: 

The problem with your code is that there are two sub functions in the re module. One is the general one and there's one tied to regular expression objects. Your code is not following either one:

The two methods are:

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

Used like so:

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

And for when you compile it before hand, as you tried, you can use:

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

Used like so:

>>> z = r.sub('blue', x)
>>> z
'The sky is blue'
Paolo Bergantino
Added the example for use with regular expressions :)
Paolo Bergantino
Way to edit my answer in.
Unknown
+4  A: 

You read the API wrong

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

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

r.sub(x, "blue")
# should be
r.sub("blue", x)
Unknown
+1. When in doubt, help(r.sub)
ojrac
+3  A: 

You have the arguments to your call to sub the wrong way round it should be:


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"

John Montgomery
+2  A: 

By the way, for such a simple example, the re module is overkill:

x= "The sky is red"
y= x.replace("red", "blue")
print y
ΤΖΩΤΖΙΟΥ
I had this in my original answer but the OP said he actually needed some more complex and this was just an example. +1 anyways though.
Paolo Bergantino