Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a string literally in Python

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.

like image 906
Ross W Avatar asked Aug 01 '11 19:08

Ross W


People also ask

How do you print a string literal in Python?

Use an f-string to print a variable with a string Within a print() statement, add f before a string literal and insert {var} within the string literal to print the string literal with the variable var inserted at the specified location. print(f"There are {a_variable} people coming.")

How do you make a string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.

How do you assign a string to a literal in Python?

String literals can be enclosed by either double or single quotes, although single quotes are more commonly used. Backslash escapes work the usual way within both single and double quoted literals -- e.g. \n \' \".

What does :: 1 mean in Python?

By artturijalli. In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world"


2 Answers

Try with:

print repr(s)
>>> 'ttaassdd\n\rssleeroo'
like image 181
GaretJax Avatar answered Oct 14 '22 00:10

GaretJax


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

like image 21
Thijs de Z Avatar answered Oct 14 '22 00:10

Thijs de Z