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.

2
  • This has already been asked, hopefully this points you in the correct direction: stackoverflow.com/questions/6477823/… Commented Jun 10, 2013 at 19:22
  • displayPattern = "something.*\s" use \s to find the newline character Commented Jun 10, 2013 at 19:26

4 Answers 4

9

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

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

Comments

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."

Comments

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)

Comments

0
print repr(string)
#or
print string.__repr__()

Hope this helps.

2 Comments

Why use string.__repr__() instead of repr(string)?
@ntpeterson I didn't realize it existed until just now. Changing it now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.