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.
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.")
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.
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 \' \".
By artturijalli. In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world"
Try with:
print repr(s)
>>> 'ttaassdd\n\rssleeroo'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With