In Python, is it possible to escape newline characters when printing a string?

前端 未结 3 867
终归单人心
终归单人心 2020-11-27 05:25

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:

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 05:53

    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

提交回复
热议问题