Trong Python, có thể thoát các ký tự dòng mới khi in một chuỗi không? (In Python, is it possible to escape newline characters when printing a string?)


問題描述

Trong Python, có thể thoát các ký tự dòng mới khi in một chuỗi không? (In Python, is it possible to escape newline characters when printing a string?)

I want the newline \n to show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen:

>>> print(line)
abc
def

but instead this:

>>> print(line)
abc\ndef

Is there a way to modify print, or modify the argument, or maybe another function entirely, to accomplish this?


參考解法

方法 1:

Just encode it with the 'string_escape' codec.

>>> print "foo\nbar".encode('string_escape')
foo\nbar

In python3, 'string_escape' has become unicode_escape.  Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding:

>>> print("foo\nbar".encode("unicode_escape").decode("utf‑8"))

unicode_escape reference

方法 2:

Another way that you can stop python using escape characters is to use a raw string like this:

>>> print(r"abc\ndef")
abc\ndef

or

>>> string = "abc\ndef"
>>> print (repr(string))
>>> 'abc\ndef'

the only proplem with using repr() is that it puts your string in single quotes, it can be handy if you want to use a quote

方法 3:

Simplest method: str_object.replace("\n", "\\n")

The other methods are better if you want to show all escape characters, but if all you care about is newlines, just use a direct replace.

(by TylermgilsonPurityLakeACEfanatic02)

參考文件

  1. In Python, is it possible to escape newline characters when printing a string? (CC BY‑SA 3.0/4.0)

#newline #Python #escaping






相關問題

如何格式化電子郵件中的字符串以便 Outlook 打印換行符? (How do I format a String in an email so Outlook will print the line breaks?)

contentEditable поле для захавання новых радкоў пры ўваходзе ў базу дадзеных (contentEditable field to maintain newlines upon database entry)

換行符 (newline character(s))

grep 如何匹配一些字母或行尾 (grep how to match some letters OR end of line)

Trong Python, có thể thoát các ký tự dòng mới khi in một chuỗi không? (In Python, is it possible to escape newline characters when printing a string?)

在 SWIFT 中遇到逗號時將字符串換行 (Break string to newline when meeting a comma in SWIFT)

行尾的'^ M'字符 ('^M' character at end of lines)

從C#中的字符串末尾刪除回車符和換行符 (Removing carriage return and new-line from the end of a string in c#)

新線路和瀏覽器/操作系統兼容性 (New lines and browser/OS compatability)

如何使用 grep 查找單詞後兩個字符之間的所有內容,而不輸出整行? (How do I find everything between two characters after a word using grep, without outputting the entire line?)

在 Perl 中寫入文件的問題 (Issues writing to a file in Perl)

在 for 循環中每 7 行換行一次 (Newline every 7 lines within a for loop)







留言討論