Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - print string to screen, include \n in output [duplicate]

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.

like image 348
SheerSt Avatar asked Jun 10 '13 19:06

SheerSt


People also ask

What does \n do in print Python?

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.

How do you print a string with a line break in Python?

Use "\n" to print a line break <a name="use-"\n""> Insert "\n" at the desired line break position.

What is \N in Python string?

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.

How do you repeat output in Python?

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.


2 Answers

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

like image 189
iurisilvio Avatar answered Oct 09 '22 10:10

iurisilvio


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."
like image 20
Óscar López Avatar answered Oct 09 '22 12:10

Óscar López