5

I have the following code:

pattern = "something.*\n" #intended to be a regular expression

fileString = some/path/to/file

numMatches = len( re.findall(pattern, fileString, 0) )

print "Found ", numMatches, " matches to ", pattern, " in file."

I want the user to be able to see the '\n' included in pattern. At the moment, the '\n' in pattern writes a newline to the screen. So the output is like:

Found 10 matches to something.*
 in file.

and I want it to be:

Found 10 matches to something.*\n in file.

Yes, pattern.replace("\n", "\n") does work. But I want it to print all forms of escape characters, including \t, \e etc. Any help is appreciated.

SheerSt
  • 3,229
  • 7
  • 25
  • 34
  • This has already been asked, hopefully this points you in the correct direction: http://stackoverflow.com/questions/6477823/python-display-special-characters-when-using-print-statement – dkroy Jun 10 '13 at 19:22
  • `displayPattern = "something.*\s"` use `\s` to find the newline character – abhishekgarg Jun 10 '13 at 19:26

4 Answers4

9

Use repr(pattern) to print the \n the way you need.

iurisilvio
  • 4,868
  • 1
  • 30
  • 36
3

Try this:

displayPattern = "something.*\\n"
print "Found ", numMatches, " matches to ", displayPattern, " in file."

You'll have to specify a different string for each case of the pattern - one for matching and one for displaying. In the display pattern, notice how the \ character is being escaped: \\.

Alternatively, use the built-in repr() function:

displayPattern = repr(pattern)
print "Found ", numMatches, " matches to ", displayPattern, " in file."
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0
print repr(string)
#or
print string.__repr__()

Hope this helps.

Drew
  • 104
  • 7
0

Also another way to use repr is with the %r format string. I would normally write this as

print "Found %d matches to %r in file." % (numMatches, pattern)
bwbrowning
  • 6,200
  • 7
  • 31
  • 36