简体   繁体   中英

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? 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). 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.

The second option (using a double backslash) causes python to specifically interpret that part of the string as a single backslash. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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