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.
The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.
Use "\n" to print a line break <a name="use-"\n""> Insert "\n" at the desired line break position.
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.
In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.
Use repr(pattern)
to print the \n
the way you need.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With