22

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.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
Ross W
  • 1,300
  • 3
  • 14
  • 24

2 Answers2

49

Try with:

print repr(s)
>>> 'ttaassdd\n\rssleeroo'
GaretJax
  • 7,462
  • 1
  • 38
  • 47
3

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

Thijs de Z
  • 377
  • 3
  • 10
  • 1
    how to add 'r' when the string is in a variable? – Rishabh Gupta Jun 09 '21 at 08:40
  • The string is in a variable (```s```) as you can see above. What do you mean exactly? – Thijs de Z Jan 18 '22 at 13:27
  • I meant, how can we add 'r' when the string we want to print is in a variable where the value is not assigned by us, but rather is given in the variable already. For example, the string variable is input to a function. – Rishabh Gupta Jan 18 '22 at 15:52
  • Right, in that case you should use ```repr``` as it's the actual function used to format the string anyway. In your case: ```print(repr(some_str_input))``` Should do. – Thijs de Z Jan 19 '22 at 18:08