Reputation: 3593
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.
Upvotes: 4
Views: 278
Reputation: 103844
>>> 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
Upvotes: 2
Reputation: 9693
Don't need a regex to replace "I'm superman"
with "############"
Try
input = "I'm superman"
print "#" * len(input)
Upvotes: 1
Reputation: 65126
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.
Upvotes: 5