0

i am not able to figure out why the below two print statements gives different results. can any one please explain me? i am just giving a small sample example. in the first print statement table is getting replaced by a special character and the second one gives correct one.

import re  

def tblcnv( str ):  
    rtval = re.sub("table", "chair", str)  
    return rtval  

rval = "<table is in the place where you sit daily "  
tblcnt = re.sub(r"<(table.*place)", tblcnv('\1'), rval)  

print tblcnt  
print tblcnv("<table is in the place where you sit daily")
4
  • Can you add the output you're seeing? Commented Jan 28, 2013 at 16:27
  • @thegrinner D:\Python>tbl.py ☺ where you sit daily <chair is in the place where you sit daily Commented Jan 28, 2013 at 16:30
  • The comment suppresses newlines - if you edit your post it will be more clear. Commented Jan 28, 2013 at 16:31
  • D:\Python>tbl.py ☺ where you sit daily <chair is in the place where you sit daily Commented Jan 28, 2013 at 16:36

3 Answers 3

2

This line:

tblcnt = re.sub(r"<(table.*place)", tblcnv('\1'), rval)

probably doesn't do what you think it should. The call to tblcnv('\1') returns '\1' which is the smiley face you see and then it replaces the first chunk of your string with said smiley face.

Sign up to request clarification or add additional context in comments.

Comments

2

When defining tblcnt, you're passing tblcnv('\1'). '\1' is the string containing a single byte with value 0x01. So the result from tblcnv is that same string.

1 Comment

You might want '\\1' or r'\1'.
1

According to the re.sub manual it takes a function which "is called for every non-overlapping occurrence of pattern". As those occurrences are actually match objects you are best of using a simple lambda expression which extracts the group(1) of the match objects and passes it to your tblcnv function.

import re

def tblcnv( str ):  
    rtval = re.sub("table", "chair", str)  
    return rtval  

rval = "<table is in the place where you sit daily "  
tblcnt = re.sub(r"<(table.*place)", lambda m: tblcnv(m.group(1)), rval)  

print tblcnt  
print tblcnv("<table is in the place where you sit daily")

2 Comments

it worked like a charm. Thanks a lot for your valuable explanation.
Would you mind to accept this answer? I would love to see this green tick. Thank you and all the best learning the awesome programming language called python!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.