简体   繁体   English

如何打印“ \\ n”而不是“ \\\\ n”

[英]how to print '\n' and not '\\n'

I am making a application where I am using some auto generate regular expressions which are multi line is the reg Ex string contains \\n . 我正在制作一个应用程序,其中我使用了一些自动生成的正则表达式,这些表达式是多行的reg Ex字符串包含\\n

Now every time i execute a generate command i would like to print the command to console also for documentation ect. 现在,每次执行生成命令时,我都希望将命令打印到控制台上以用于文档编制等。

INFO: Command execute: (regular expression)

however if i just print my Reg Ex string containing the \\n I also get newline in the printout which is not desirable. 但是,如果我只打印包含\\n Reg Ex字符串,则在打印输出中还会出现换行符,这是不希望的。

INFO: Command execute: (regular expre
ssion)

I can get it to print the newline \\n by adding an escape char making it \\\\n and it is also how it looks on the print out. 我可以通过添加转义字符使其\\\\n来打印换行符\\n ,这也是它在打印输出上的外观。

INFO: Command execute: (regular expre\\nssion)

This is not desirable either. 这也不可取。 What I am looking for is to be able to print it like following. 我正在寻找的是能够像下面这样打印。

INFO: Command execute: (regular expre\nssion)

Is this possible ? 这可能吗 ?

regards 问候

Use the built-in function repr() to get the string that would reproduce that object when evaluated: 使用内置函数repr()获取评估时将重现该对象的字符串:

>>> text = 'INFO: Command execute: (regular expre\nssion)'
>>> print(text)
INFO: Command execute: (regular expre
ssion)
>>> print(repr(text))
'INFO: Command execute: (regular expre\nssion)'

You can try this. 你可以试试看 String prefix r makes it ignore all escapes. 字符串前缀r使其忽略所有转义。

a = r"Hello\nworld"
print a # Hello\nworld

If you still need new lines while using r , you can use triple quote sintax 如果在使用r仍需要换行,则可以使用三引号sintax

b = r"""Big \n long
\n
string"""
print b
# Big \n long
# \n
# string 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM