Python - 将字符串打印到屏幕,在输出中包含 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17031172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - print string to screen, include \n in output
提问by SheerSt
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:
我希望用户能够看到模式中包含的 '\n'。目前,模式中的 '\n' 将换行符写入屏幕。所以输出是这样的:
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.
是的,pattern.replace("\n", "\n") 确实有效。但我希望它打印所有形式的转义字符,包括 \t、\e 等。感谢任何帮助。
采纳答案by iurisilvio
Use repr(pattern)to print the \nthe way you need.
用于repr(pattern)以\n您需要的方式打印。
回答by óscar López
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:
或者,使用内置repr()函数:
displayPattern = repr(pattern)
print "Found ", numMatches, " matches to ", displayPattern, " in file."
回答by Drew
print repr(string)
#or
print string.__repr__()
Hope this helps.
希望这可以帮助。
回答by bwbrowning
Also another way to use repr is with the %r format string. I would normally write this as
使用 repr 的另一种方法是使用 %r 格式字符串。我通常会这样写
print "Found %d matches to %r in file." % (numMatches, pattern)

