Python escape character mixed with backslash n for newline - python

I have a function in python which return a huge text table in a neat format.
My output has multiple \n an \t.
I can print out the output and it would have preserved the table format. However, in a python interactive window,I want to call the function and not store it the output but display it on console screen.
What I see is \\n instead of \n.
I understand that \ is an escape character.But what do I do make my python interactively handle the formatting.
eg. for descriptive purpose only
def print_table():
return table;
>>> print_table() #is there anything I can do here to have neat display
>>> r0c0 r0c1 \nr1c0 r1c1
>>> print (print_table())
>>> r0c0 r0c1
r1c0 r1c1
I am using Python3.6

Have you tried pretty printer?
from pprint import pprint
pprint(print_table)

You could store the result in a variable
>>> def print_table():
>>> return table
>>> my_table = print_table()
>>> print(my_table)
>>> r0c0 r0c1
r1c0 r1c1

Related

How do I get '\\\\host\\printer' out of a string var of '\\host\printer' in python 2.7.5?

How do I get '\\\\host\\printer' out of a string var of '\\host\printer' in python 2.7.5?
My program takes in a string argument, "\\host\printer", and I need to convert it to "\\\\host\\printer" in order to submit it as a JSON doc to a web endpoint.
Seems simple enough, but python won't let me. Here's what happens:
>>> data = '\\host\printer'
>>> print data.replace('\\','\\\\')
\\host\\printer
Now, if this data var was assigned a raw string, it'd work fine:
>>> data = r'\\host\printer'
>>> print data.replace('\\','\\\\')
\\\\host\\printer
However, since data is an input argument, I can't make it a raw string. I've tried several tricks found on SO to convert it to a raw string, but no luck with the final result, as shown below.
encode() doesn't help:
>>> data = '\\host\printer'
>>> data = data.encode('string-escape')
>>> print data.replace('\\','\\\\')
\\\\host\\\\printer
nor does repr():
>>> data = '\\host\printer'
>>> data = repr(data)
>>> print data.replace('\\','\\\\')
'\\\\host\\\\printer'
nor does re.escape():
>>> import re
>>> data = '\\host\printer'
>>> data = re.escape(data)
>>> print data.replace('\\','\\\\')
\\\\host\\\\printer
When you write this:
>>> data = '\\host\printer'
You end up with data containing the literal string \host\printer, because in Python \ is an escape character, and when you want a single \ you need to write \\. You can disable this behavior by using a raw string, or by escaping \ whenever you use it. So you can write:
>>> data = '\\\\host\\printer'
Or you can write:
>>> data = r'\\host\printer'
Since you want the literal string \\\\host\\printer, you need to replace every instance of \ with \\. Which means you can write this:
>>> newdata = data.replace('\\', '\\\\')
And that gets you:
>>> print newdata
\\\\host\\printer
The String Literals section of the docs has some details on the above.

Print all characters in a string

Is there a way to print all characters in python, even ones which usually aren't printed?
For example
>>>print_all("skip
line")
skip\nline
Looks like you want repr()
>>> """skip
... line"""
'skip\nline'
>>>
>>> print(repr("""skip
... line"""))
'skip\nline'
>>> print(repr("skip line"))
'skip\tline
So, your function could be
print_all = lambda s: print(repr(s))
And for Python 2, you need from __future__ import print_function
Even easier, cast it to a raw string by using "%r", raw strings treat backslashes as literal characters:
print("%r" % """skip
line""")
skip\nline
Additionally, use !r in a format call:
print("{0!r}".format("""skip
line"""))
for similar results.

how to extract string inside single quotes using python script

Have a set of string as follows
text:u'MUC-EC-099_SC-Memory-01_TC-25'
text:u'MUC-EC-099_SC-Memory-01_TC-26'
text:u'MUC-EC-099_SC-Memory-01_TC-27'
These data i have extracted from a Xls file and converted to string,
now i have to Extract data which is inside single quotes and put them in a list.
expecting output like
[MUC-EC-099_SC-Memory-01_TC-25, MUC-EC-099_SC-Memory-01_TC-26,MUC-EC-099_SC-Memory-01_TC-27]
Thanks in advance.
Use re.findall:
>>> import re
>>> strs = """text:u'MUC-EC-099_SC-Memory-01_TC-25'
text:u'MUC-EC-099_SC-Memory-01_TC-26'
text:u'MUC-EC-099_SC-Memory-01_TC-27'"""
>>> re.findall(r"'(.*?)'", strs, re.DOTALL)
['MUC-EC-099_SC-Memory-01_TC-25',
'MUC-EC-099_SC-Memory-01_TC-26',
'MUC-EC-099_SC-Memory-01_TC-27'
]
You can use the following expression:
(?<=')[^']+(?=')
This matches zero or more characters that are not ' which are enclosed between ' and '.
Python Code:
quoted = re.compile("(?<=')[^']+(?=')")
for value in quoted.findall(str(row[1])):
i.append(value)
print i
That text: prefix seems a little familiar. Are you using xlrd to extract it? In that case, the reason you have the prefix is because you're getting the wrapped Cell object, not the value in the cell. For example, I think you're doing something like
>>> sheet.cell(2,2)
number:4.0
>>> sheet.cell(3,3)
text:u'C'
To get the unwrapped object, use .value:
>>> sheet.cell(3,3).value
u'C'
(Remember that the u here is simply telling you the string is unicode; it's not a problem.)

String formating with Python's escape sequence

For clarification purposes, I am rewriting from scratch with additional information.
Consider the following:
y = hex(1200)
y
'0x4b0'
I need to replace that first 0 of y with a '\' to make it look like '\x04b0'. I am communicating with an instrument over RS-232 serial which takes parameters strictly in that format ('\xSumCharsHere'). Python won't let me do the following.
z = '\x' + y[2:]
ValueError: invalid \x escape
The following is not acceptable, because it still has '\\' in the actual value assigned to z.
z = '\\' + y[1:]
z
'\\x4b0'
The end goal is to send a command like this to my serial port:
s.write(z) # s is a serial object
s.write('\x04b0') # This call is an equivalent of the call above
s.write('\\x04b0') # This command will not work
Your last bit of code doesn't do what you think it does:
>>> x = hex(1200)
>>> y = '\\' + x[1: len(x)]
>>> y
'\\x4b0'
>>> print y
\x4b0
When you type the name of a variable in the Python console, Python prints the string's representation as Python code, which is why you see two backslashes -- a literal backslash in a Python string is escaped by another leading backslash. This code does in fact work, the representation of the result is just throwing you off.
However, I would suggest you use this snippet instead, since yours is omitting leading zeroes:
>>> y = '\\x%04x' % 1200
>>> print y
\x04b0
Your last code bit is correct, and it can be alternatively written using a raw string:
y = r'\x' + x[2: len(x)]
As cdhowie said in his answer:
When you type the name of a variable in the Python console, Python prints the string's representation as Python code. This code does in fact work, the representation of the result is just throwing you off.
This is an alternative for hand-writing escape sequences, however, and one I think is slightly better coding practice as it is much more readable.
The latter will work. In the console, Python uses repr() to print objects, which in this case will show the double slash. Do print y in the console and you'll see that it outputs properly.
You can also clean up your first example a bit:
y = "\\x" + x[2:]
Or the second:
y = "\\" + x[1:]
If you are just trying to get the string \0x4b0 as the representation at the console, you need to actually call print on it at the console:
>>> s='\\0{}'.format(hex(1200)[1:])
>>> s
'\\0x4b0'
>>> print s
\0x4b0
>>> s2='\\0'+hex(1200)[1:]
>>> s2
'\\0x4b0'
>>> print s2
\0x4b0
If you just FORM the string in the console (i.e., it does not go through print), Python is showing you its representation:
>>> '\\0{}'.format(hex(1200)[1:])
'\\0x4b0'
>>> repr(s2)
"'\\\\0x4b0'"
>>> s2
'\\0x4b0'
Edit (based on your comment):
I assume this is an old HP plotter?
Don't be confused by what the shell is showing as your string.
You state that you want to produce a string of \x<someNumGoesHere> (or is it \x0<someNumGoesHere> with a leading 0?)
Here is how:
>>> def angle_string(angle):
... return '\\0{}'.format(hex(angle)[1:])
...
>>> angle_string(1200)
'\\x04b0'
>>> print _
\x04b0
>>> angle_string(33)
'\\x021'
>>> print _
\x021
When you send the string to your device (through the OS file/print like service to the RS232 port), it will be as you format it.
Edit 2
String interpolation is the process where these string literals:
>>> s1
'\n\n\t\tline'
Get translated to this:
>>> print s
line
Logically, these literal characters are single characters:
>>> s1[0]
'\n'
>>> len('\\')
1
My guess is that the way you have opened the serial port s is using the strings is raw mode, so the string \\x0123 is being sent that way (raw mode) vs being interpreted as \x0123
You might try as a work around this:
>>> cmd=chr(92)+'0'+hex(1200)[1:]
>>> s.write(cmd)
I think you also need to open the serial port in FileLike mode so that the string literals are sent as proper single characters.

Convert special characters in to original form in python

Suppose I had a string for example:
>>> stri = "日本"
>>> res = stri
>>> res
'\xe6\x97\xa5\xe6\x9c\xac'
Now I want to convert the result in res back to the form in "日本".
(Assuming that you're using Python 2.x on a UTF-8 console):
Nothing has been converted, and there is no need to convert anything back; what you're seeing is the internal representation of the string. Try printing it.
>>> stri = "日本"
>>> stri
'\xe6\x97\xa5\xe6\x9c\xac'
>>> print(stri)
日本
To clarify:
If you enter the name of a Python variable in the console, the console will print the repr of that variable. If you want to print the variable in human-readable form, use print instead. There is no difference in the way the variable is stored, therefore there's nothing to convert.
That is the expected behaviour - console doesn't print variable in unicode. If you actually print it out you'll see that the correct chars are still there. The console automatically uses repr on every variable before printing it out. You can verify that yourself by doing print(repr...)) like the example below:
>>> stri = "日本"
>>> stri
'\xe6\x97\xa5\xe6\x9c\xac'
>>> print stri
日本
>>> print repr(stri)
'\xe6\x97\xa5\xe6\x9c\xac'
>>>
Like Tim said, the characters haven't been converted.
This article should help you understand what's happening

Categories

Resources