views:

154

answers:

3

How can I replace the contents of strings with #'s in Python? Assume no comments, no multiple lines for one string. Like if there is a line in a python file:

print 'Hello' + "her mom's shirt".

This will be translated into:

print '#####' + "###############".

It's like a filter to deal with every line in a python file.

+4  A: 

If you're using Python and the thing you're parsing is Python there's no need to use regexp since there's a built-in parser.

Matti Virkkunen
+1  A: 

Don't need a regex to replace "I'm superman" with "############"

Try

input = "I'm superman"
print "#" * len(input)
Day
Thank you for your help, but the case is I need to practice my python skill
antonio081014
Well if you wanted to do above with a regex it would be something like `print re.sub('.', '#', input)
Day
@Day, you're missing the point. The source is supposed to be a python file from which the strings are to be parsed.
aaronasterling
@AaronMcSmooth, yes the question changed while I was writing my answer. You got to be quick round here. I was responding to antonio's comment on his own question at the time.
Day
+2  A: 
>>> import re
>>> s="The Strings"
>>> s=re.sub("\w","#",s)
>>> s
'### #######'
>>> s='Hello' + "her mom's shirt"
>>> s
"Helloher mom's shirt"
>>> re.sub("\w","#",s)
"######## ###'# #####"

----Edit

OK, Now I understand that you want the output to be from a Python file. Try:

import fileinput
import re 

for line in fileinput.input():
    iter = re.finditer(r'(\'[^\']+\'|"[^"]+")',line)
    for m in iter:
       span = m.span()
       paren = m.group()[0]
       line = line[:span[0]]+paren+'#'*(span[1]-span[0]-2)+paren+line[span[1]:] 
       print line.rstrip()

This does not deal with line breaks, the """ form, and is only tested again 1 or two files I have...

In general, it is better to use a parser for this kind of job.

Best

drewk
+1, was writing the exact same thing
Matti
What I expect is just the characters in string will be replaced, but not the result after combination of the two strings.
antonio081014
@antonio081014: Based on the responses you are getting, it should be very clear to you that your question is not clear. You said in your post "It's like a filter to deal with every line in a python file." Are you saying you want to process a group of Python source files in another script?
drewk
@drewk: What I want is write this python script to deal with python file.
antonio081014
I think the question is quite clear now that he added the examples.
Matti Virkkunen
@drewk: Thank you very much. I finally got it. I really appreciate.
antonio081014
@antonio081014 you are welcome!
drewk