Python Eval/Exec function not resolving - python

I'm trying to use eval function to execute a loop. It gives a syntax error
list_subjects = (element.upper() for element in list(score_card_data['subject_id']))
for i,sub in enumerate(list_subjects) :
print(("bins_{1:s}").format(i,sub))
print("list(score_card_data.loc[score_card_data['subject_id'] == {1:s}, 'bin_list'])").format(i,sub)
eval("("bins_{1:s}").format(i,sub) = "list(score_card_data.loc[score_card_data['subject_id'] == {1:s}, 'bin_list'])").format(i,sub)")
File "<ipython-input-192-529c79a094e4>", line 5
eval("("bins_{1:s}").format(i,sub) = "list(score_card_data.loc[score_card_data['subject_id'] == {1:s}, 'bin_list'])").format(i,sub)")
^
SyntaxError: invalid syntax
How do I resolve the 2 print statements in one eval function

You get a syntax error because you try to use the same type of quotes inside a string that is used to delimit the string literal in your code.
You have those options:
Use single quotes inside the string and double quotes to delimit it:
eval("' '.join('some', 'words')")
Use double quotes inside the string and single quotes to delimit it:
eval('" ".join("some", "words")')
Use any quotes inside the string and any quotes (the same type on the left and right side of course) to delimit it, but escape all quotation marks inside the string using a backslash:
eval('\' \'.join(\'some\', \'words\')')
eval("\" \".join(\"some\", \"words\")")
Use any quotes inside the string and "triple quotes" (either three single quotes ''' or three double quotes """, same type on the left and right side of course) to delimit it:
eval("""" ".join("some", "words")""")
eval("""' '.join('some', 'words')""")
eval('''' '.join('some', 'words')''')
eval('''" ".join("some", "words")''')

Related

Loads json with double quotes in it

I'm trying to parse a JSON string that contains double quotes in it:
import json
x = '''{"key":"Value \"123\" "}'''
When I try to load this JSON using the following statement
y = json.loads(x)
It raises the following exception:
Expecting ',' delimiter: line 1 column 15 (char 14)
As per my understanding, it is due to the double quotes around 123 in JSON. Also, I tried replacing the \" (backslash quote) with some other stuff as well but all in vain
x.replace('\"',"'")
as it also replaced the double quotes that are present around key and value as well
'''{"key": "Value \"123\" "}''' ---Replacing--> '''{'key':'Value '123' '}''')
I can not change anything in the input string. That's coming from an API.
Any help would be highly appreciated, I'm stuck with this for quite a time now. Thanks in advance...
\" within a string is simply a double quotation mark. You need to add another backslash:
x = '''{"key":"Value \\"123\\" "}'''

In Python if you return a string,it will be displayed with quotes around it but If you print the string, it will not be shown with quotes. why? [duplicate]

This question already has answers here:
In the Python interpreter, how do you return a value without single quotes around it?
(2 answers)
Closed 3 years ago.
In the Python interactive prompt, if you return a string, it will be displayed with quotes around it. But if you just print the string, it will not be shown with quotes. Why?
>>> a='world'
>>> a
'world'
>>> print(a)
world
Simply put:
The quotes allow python to treat whatever is inside of them as a 'string literal'; that way, if we wanted to write a string like 'print([0, 1, 2])' we would actually literally get print([0, 1, 2]) as a reply instead of [0, 1, 2]. The print function in python only prints the string literal out to the console for the user to see, since the user knows this is a string.
If we wanted to include quotes in the print, we could use a mixture of ' and " (single vs. double) quotes. For example, we could 'define' the string literal / tell python its going to be a literal with outer quotes "" then inside of that put 'testing...'. So if we set that equal to a variable for clarity (example = "'testing...'") now print(example), as you can see we would get the single quotes (') included in the output.
return function holds the value of the string and that value is the string.
print function doesn't hold the value, it removes the string quotes leading and trailing then displays the value on the screen.
as for example,
check the (strip function) of python, it helps to remove leading and trailing values

Why in Python 3, repr(repr(obj)) is repr(obj) wrapped in double quotes when obj is a non-empty mapping proxy? [duplicate]

This question already has answers here:
Understanding difference between Double Quote and Single Quote with __repr__()
(3 answers)
Closed 3 years ago.
In Python 3, most of the time, the result of repr(repr(obj)) will be repr(obj) wrapped in single quotes. But when obj is a non-empty mapping proxy repr(repr(obj)) is wrapped in double quotes. Why?
This is a Windows 10 server running Python 3.7 on Wing IDE 101.
mappingproxy = type(object.__dict__)
#Single quotes for undefined mapping proxies
print(repr("mappingproxy({})"))
'mappingproxy({})'
#Double quotes for defined mapping proxies
print(repr(repr(object.__dict__)))
<<< "mappingproxy({...})"
#For custom empty mapping proxies...
print(repr(repr(mappingproxy({}))))
<<< 'mappingproxy({})'
#...single, at least for ones evaluating to False
#For mapping proxies evaluating to True...
print(repr(repr(mappingproxy({'a':1, 'b':2}))))
<<< "mappingproxy({'a': 1, 'b': 2})"
#...double
#For non-existant non-empty ones...
print(repr("mappingproxy({'a':1})"))
<<< "mappingproxy({'a':1})"
#...double
#Why is that?
The resultants from the print statements start with "<<<".
By the way, I think I can derive an empty mapping proxy representation's representation is wrapped in single quotes.
Python's string repr defaults to single quotes, but will switch to double quotes if it contains any single quotes so it doesn't have to escape them with a backslash. (Otherwise the first internal single quote would end the string.)
But if it contains both double and single quotes, it will use the default single quotes and escape them with a backslash internally.
Note that your mappingproxy repr examples contain single-quoted strings, except for the empty one. That's internal single quotes.

Replace double backslash in string literal with single backslash

I'm trying to print a string that contains double backslash (one to escape the other) such that only one of the backslashes are printed. I thought this would happen automatically, but I must be missing some detail.
I have this little snippet:
for path in self.tokenized:
pdb.set_trace()
print(self.tokenized[path])
When I debug with that pdb.set_trace() I can see that my strings have double backslashes, and then I enter continue to print the remainder and it prints that same thing.
> /home/kendall/Development/path-parser/tokenize_custom.py(82)print_tokens()
-> print(self.tokenized[path])
(Pdb) self.tokenized[path]
['c:', '\\home', '\\kendall', '\\Desktop', '\\home\\kendall\\Desktop']
(Pdb) c
['c:', '\\home', '\\kendall', '\\Desktop', '\\home\\kendall\\Desktop']
Note that I'm writing a parser that parses Windows file paths -- thus the backslashes.
This is what it looks like to run the program:
kendall#kendall-XPS-8500:~/Development/path-parser$ python main.py -f c:\\home\\kendall\\Desktop
The issue you are having is that you're printing a list, which only knows one way to stringify its contents: repr. repr is only designed for debugging use. Idiomatically, when possible (classes are a notable exception), it outputs a syntactically valid python expression that can be directly fed into the interpretter to reproduce the original object - hence the escaped backslashes.
Instead, you need to loop through each list, and print each string individually.
You can use str.join() to do this for you.
To get the exact same output, minus the doubled backslashes, you'd need to do something like:
print("[{0}]".format(", ".join(self.tokenized[path])))

Weird issue during parsing a path in Python

Given this variables:
cardIP="00.00.00.00"
dir="D:\\TestingScript"
mainScriptPath='"\\\\XX\\XX\\XX\\Testing\\SNMP Tests\\Python Script\\MainScript.py"'
When using subprocess.call("cmd /c "+mainScriptPath+" "+dir+" "+cardIP) and print(mainScriptPath+" "+dir+" "+cardIP) I get this:
"\\XX\XX\XX\Testing\SNMP Tests\Python Script\MainScript.py" D:\TestingScript 00.00.00.00
which is what I wanted, OK.
But now, I want the 'dir' variable to be also inside "" because I am going to use dir names with spaces.
So, I do the same thing I did with 'mainScriptPath':
cardIP="00.00.00.00"
dir='"D:\\Testing Script"'
mainScriptPath='"\\XX\\XX\\XX\\Testing\\SNMP Tests\\Python Script\\MainScript.py"'
But now, when I'm doing print(mainScriptPath+" "+dir+" "+cardIP) I get:
"\\XX\XX\XX\Testing\SNMP Tests\Python Script\MainScript.py" "D:\Testing Script" 00.00.00.00
Which is great, but when executed in subprocess.call("cmd /c "+mainScriptPath+" "+dir+" "+cardIP) there is a failure with 'mainScriptPath' variable:
'\\XX\XX\XX\Testing\SNMP' is not recognized as an internal or external command...
It doesn't make sense to me.
Why does it fail?
In addition, I tried also:
dir="\""+"D:\\Testing Script"+"\""
Which in 'print' acts well but in 'subprocess.call' raise the same problem.
(Windows XP, Python3.3)
Use proper string formatting, use single quotes for the formatting string and simply include the quotes:
subprocess.call('cmd /c "{}" "{}" "{}"'.format(mainScriptPath, dir, cardIP))
The alternative is to pass in a list of arguments and have Python take care of quoting for you:
subprocess.call(['cmd', '/c', mainScriptPath, dir, cardIP])
When the first argument to .call() is a list, Python uses the process described under the section Converting an argument sequence to a string on Windows.
On Windows, an args sequence is converted to a string that can be
parsed using the following rules (which correspond to the rules used
by the MS C runtime):
Arguments are delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted
string can be embedded in an argument.
A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the
number of backslashes is odd, the last backslash escapes the next
double quotation mark as described in rule 3.
This means that passing in your arguments as a sequence makes Python worry about all the nitty gritty details of escaping your arguments properly, including handling embedded backslashes and double quotes.

Categories

Resources