Python - 将字符串打印到屏幕上,输出中包含 \n

5

我有如下代码:

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

我希望用户能够看到模式中包含的“\n”。目前,“\n”在模式中会写入换行符到屏幕上。因此输出结果如下:
Found 10 matches to something.*
 in file.

and I want it to be:

Found 10 matches to something.*\n in file.

是的,pattern.replace("\n", "\n") 是可以运行的。但我希望它可以打印出所有转义字符,包括 \t, \e 等等。感谢任何帮助。


这个问题已经被问过了,希望这能指引你正确的方向:https://dev59.com/smw15IYBdhLWcg3wpNYB - dkroy
displayPattern = "something.*\s" 使用 \s 查找换行符 - abhishekgarg
4个回答

9
使用 repr(pattern) 来打印你需要的 \n

3

试试这个:

displayPattern = "something.*\\n"
print "Found ", numMatches, " matches to ", displayPattern, " in file."

对于每种模式,您需要指定不同的字符串-一种用于匹配,一种用于显示。在显示模式中,请注意如何转义\字符:\\

或者,使用内置的repr()函数:

displayPattern = repr(pattern)
print "Found ", numMatches, " matches to ", displayPattern, " in file."

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

希望这能有所帮助。

1
为什么要使用 string.__repr__() 而不是 repr(string) - Nick Peterson
@ntpeterson 直到现在我才意识到它的存在。现在正在更改。 - Drew

0

另一种使用 repr 的方法是使用 %r 格式化字符串。我通常会这样写

print "Found %d matches to %r in file." % (numMatches, pattern)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接