How to replace characters in strings with '# using regex in Python

How to replace string contents with # in Python? Avoid comments; there are no multiple lines for one line. For example, if there is a line in the python file:

 print 'Hello' + "her mom shirt". 

This will be translated into:

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

It as a filter processes every line in the python file.

+4
source share
3 answers
 >>> import re >>> s="The Strings" >>> s=re.sub("\w","#",s) >>> s '### #######' >>> s='Hello' + "her mom shirt" >>> s "Helloher mom shirt" >>> re.sub("\w","#",s) "######## ###'# #####" 

---- Edit

OK, Now I understand that you want the result 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 apply to line breaks, the form "" and only 1 or two files that I have are checked ...

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

The best

+2
source

If you use Python and what you parse, then Python does not need to use regexp, since there is a built-in parser .

+5
source

No regex needed to replace "I'm superman" with "############"

Try

 input = "I'm superman" print "#" * len(input) 
+1
source

All Articles