Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with my attempt to do a string replace operation in Python?

Tags:

python

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"?

like image 320
mike Avatar asked Feb 06 '26 04:02

mike


2 Answers

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'
like image 126
Paolo Bergantino Avatar answered Feb 08 '26 19:02

Paolo Bergantino


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)
like image 30
Unknown Avatar answered Feb 08 '26 18:02

Unknown