简体   繁体   English

Python-如何显示“ \\ n”?

[英]Python - How to get “\n” to display?

How do I print a string that has \\n in it without it actually going to a new line? 我如何打印其中带有\\ n的字符串而又不实际换行呢? For example, how do I do: 例如,我该怎么做:

print("You can use \n for a new line")

without it doing a line break? 没有它做换行?

print(r"You can use \n for a new line")

or 要么

print("You can use \\n for a new line")

The first option (putting the r in front of the string) causes all the backslashes in the string to be simply interpreted as a backslash character instead of an escape character to do something special (see https://stackoverflow.com/a/2081708/6735980 for more info on that). 第一个选项(将r放在字符串前面)会使字符串中的所有反斜杠简单地解释为反斜杠字符,而不是转义字符,以执行特殊操作(请参阅https://stackoverflow.com/a/2081708) / 6735980,以获取更多信息)。 This is especially useful, for example, if you have multiple instances of \\n in the string and you want them all to simply be interpreted as exactly those two characters instead of a newline. 例如,如果您在字符串中有多个\\n实例,并且希望将它们全部简单地解释为恰好是这两个字符而不是换行符,则此功能特别有用。

The second option (using a double backslash) causes python to specifically interpret that part of the string as a single backslash. 第二个选项(使用双反斜杠)使python专门将字符串的该部分解释为单个反斜杠。 This is useful if you want more control than what the first solution offers (for example, if within the same string you have one place where you really just want to print \\n , and a different part in the same string where you do want to use a newline). 如果您要控制的内容比第一种解决方案所提供的更多,这将很有用(例如,如果在同一字符串中您确实只想打印\\n ,而在同一字符串中您想要打印的另一部分又有一个地方,使用换行符)。

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

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