How to print a string literally in Python

大城市里の小女人 提交于 2019-11-30 01:17:42

问题


this is probably really simple but I can't find it.

I need to print what a string in Python contains. I'm collecting data from a serial port and I need to know if it is sending CR or CRLF + other control codes that are not ascii.

As an example say I had

s = "ttaassdd\n\rssleeroo"

then I would like to do is:

print s

Where it would show the \n\r rather than covert them into escape characters.


回答1:


Try with:

print repr(s)
>>> 'ttaassdd\n\rssleeroo'



回答2:


Saving your string as 'raw' string could also do the job.

(As in, by putting an 'r' in front of the string, like the example here)


    >>> s = r"ttaassdd\n\rssleeroo"
    >>> print s
    ttaassdd\n\rssleeroo



来源:https://stackoverflow.com/questions/6903551/how-to-print-a-string-literally-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!