Python - print string to screen, include \n in output
51,764
Solution 1
Use repr(pattern)
to print the \n
the way you need.
Solution 2
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."
Author by
SheerSt
Updated on June 11, 2020Comments
-
SheerSt about 4 years
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.
-
dkroy about 11 yearsThis has already been asked, hopefully this points you in the correct direction: stackoverflow.com/questions/6477823/…
-
abhishekgarg about 11 years
displayPattern = "something.*\s"
use\s
to find the newline character
-
-
Nick Peterson about 11 yearsWhy use
string.__repr__()
instead ofrepr(string)
? -
Drew about 11 years@ntpeterson I didn't realize it existed until just now. Changing it now.