在Python中,打印字符串时是否可以转义换行符? [英] In Python, is it possible to escape newline characters when printing a string?
本文介绍了在Python中,打印字符串时是否可以转义换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要打印从别处检索的字符串时显式地显示换行符 \\\
。所以如果这个字符串是'abc\\\
def'我不希望发生这种情况:
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
而是这样:
>>> print(line)
abc\ndef
有没有办法修改打印,或修改参数或完全可能是另一个功能来实现这一点?
Is there a way to modify print, or modify the argument, or maybe another function entirely, to accomplish this?
推荐答案
另一种可以使用转义字符停止python的方法是使用这样的原始字符串:
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'
只有使用 repr() / code>是将您的字符串放在单引号中,如果要使用引号
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
这篇关于在Python中,打印字符串时是否可以转义换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文