String evaluation with quotes - python

I would like to evaluate a string that contains double quotes, for example as a function parameter or in an assignment:
argument = "string with \"quotes\"" # any value, e.g., read from file.
value = eval("\"" + argument + "\"")
fails:
string with "quotes"
^
SyntaxError: invalid syntax
I know I could use value = eval("\'" + argument + "\'") instead, but now this is going to fail when argument = "string with 'quotes'".
And I would like something robust that works with any string argument (e.g., read in a file) with the objective to actually use it as a function (string) parameter, maybe like that: eval("f(" + "\"" + argument + "\"" + ")").

I don't think this is your intended result, but maybe something like this?
backslash="\\"
argument = "some " + backslash + "\"data" + backslash + "\" quoted data"
value = eval("\"" + argument + "\"")
print(value)

Related

tips needed to write the function quote this

Write a function called "quote_this" that accepts two
arguments: a string representing a quote (not surrounded
by quotation marks) and a string of a name. The function
should return a new string with the quote surrounded by
quotation marks (") followed by a dash and the given
name in python.
don't know how to go about starting to solve this.any help
This should work:
def quote_this(quote,name):
return '"' + quote + '" - ' + name
In which quote represents the string of your quote and name the name of the author
def quote_this(quote_string, name):
return '\"' + str(quote_string) + '\"' + ' - ' + str(name)
quote_this('this', 'John')
You should really look into Google or read a book for this. It's really simple. Also, provide a sample code next time.

exec with ';' in python

I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )
list = ["abc","xyz","pqr"]
str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated
exec (str)
My problem here is, with exec statement, it prints only "xyz" , because of the semi colon. what is the best way to solve this, so that the exec statement prints "xyz;pqr"
You are generating the following code:
print list[0];list[2]
Note that the ; is not quoted. Since a ; is used by Python to separate multiple simple statements on a line, Python executes the print list[0] first, then list[2] (which ends up doing nothing).
You'd have to generate this code instead:
print list[0] + ';' + list[2]
which you could do with:
str = "print " + "list[0]" + " + ';' + " + "list[2]"
However, you should not be using code generation at all. Use standard Python methods to join or format a string. You could use str.format():
print '{};{}'.format(list[0], list[2])
or you could use str.join():
print ';'.join([list[0], list[2]])
If you must vary what code is executed based on some other variables, try to avoid exec still. You could use from __future__ import print_function or encapsulate the print statement in a new function, then call functions dynamically. You can always use a dispatch table to map a string to a function to call, for example.
Try this:
str = "print" + "list[0]" + "';'" + "list[2]"
or
str = "print" + "list[0]" + "/;" + "list[2]"
The problem here is that Python optionally allows semicolons to delimit two separate statements (Compound statements). So when you use exec on the evaluated statement print "abc";"xyz", Python thinks they are two separate statements, hence, only printing "abc".
You could use single quotes around the semicolon to show that it is a string and concatenate them with their surrounding strings:
# Refrain from using list and str as they are built-ins
l = ["abc", "xyz", "pqr"]
s = "print " + "l[0]" + "+';'+" + "l[2]"
exec(s)

Python insert "\" in string

I'm trying to insert a backslash in a string but when I do this:
s1='cn=Name Surname (123)'
s1[:17] + '\' + s1[17:]
I get
SyntaxError: EOL while scanning string literal
Also, tried this but it inserts 2 backslashes
s1[:17] + '\\' + s1[17:]
The final string should look like this
s1='cn=Name Surname \(123\)'
Here:
>>> s1 = 'cn=Name Surname (123)'
>>> x = s1[:16]+'\\'+s1[16:-1]+'\\'+s1[-1:]
>>> x
'cn=Name Surname \\(123\\)'
>>> print x
cn=Name Surname \(123\)
>>>
You have to print the string. Otherwise, you will see \\ (which is used in the interpreter to show a literal backslash).
>>> s1='cn=Name Surname (123)'
>>> s1[:17] + '\\' + s1[17:]
'cn=Name Surname (\\123)'
It seems like two backslash, but it's actually containing only one backslash.
>>> print(s1[:17] + '\\' + s1[17:])
cn=Name Surname (\123)
>>> print s1[:17] + '\\' + s1[17:-1] + '\\' + s1[-1:]
cn=Name Surname (\123\)
If you're just entering it in the python command line interpreter and pressing enter, it will show up as two backslashes because the interpreter shows the escape character. However, if you saved it to a file, or if you used it in a "print" command it will suppress the escape character and print the actual value, which in this case is just one backslash.
Can something like this suffice?
print(s1.replace('(', '\\(').replace(')', '\\)'))
for folder in Chart_Folders:
files = os.listdir(path + '\\' + folder)
print(files)
indeed this works

Function equivalent to prepending string with "r" in Python

It's great that I can write
s = r"some line\n"
but what is the functional equivalent to preprending with r? For example:
s = raw_rep( s )
There isn't one. The r is an integral part of the string literal token, and omitting it is a lossy operation.
For example, r'\n', r'\12' and r'\x0a' are three different strings. However, if you omit the r, they become identical, making it impossible to tell which of the three it was to begin with.
For this reason, this is no method that would reconstruct the original string 100% of the time.
def raw_rep(s):
quote = '"' if "'" in s else "'"
return 'r' + quote + s + quote
>>> print raw_rep(r'some line\n')
r'some line\n'

Python: Using strings as an object argument?

Essentially my problem is as follows...
In Python, I have a function that will return an output string in the following form:
'union(symbol(a), symbol(b))'
The function forms found within this string actually exist in an object class called RegExTree. Further this class contains a function to construct a tree data structure using the function "construct()" as shown below:
tree = RegExTree()
tree.construct(union(symbol(a), symbol(b))
The above two lines of code would work normally, constructing a tree based on parsing the arguments within the construct function. I want to pass in a string in a similar fashion, perhaps this line of code illustrates what I want:
tree = RegExTree()
expression = 'union(' + 'symbol(' + 'a' + ')' + ', ' + 'symbol(' + 'b' + ')' + ')'
tree.construct(expression)
Right now the way I have the code written as above it yields an error (in the Linux terminal) as follows:
$ Attribute Error: 'str' object has no attribute 'value'
Can you coerce Python to interpret the string as a valid argument/line of code. In essence, not as string, but as object constructors.
Is there a way to get Python to interpret a string as rather something that would have been parsed/compiled into objects and have it construct the objects from the string as if it were a line of code meant to describe the same end goal?
Is what I'm asking for some kind of back-door type conversion? Or is what I'm asking not possible in programming languages, specifically Python?
EDIT: Using Michael's solution posited below that involves "eval()", there is one way to hack this into form:
tree = RegExTree()
a = 'a'
b = 'b'
expression = 'union(' + 'symbol(' + a + ')' + ', ' + 'symbol(' + b + ')' + ')'
tree.construct(eval(expression))
Is there a better way of doing this? Or is it just that the nature of my output as string representing functions is just not a good idea?
[Thanks martineau for the correction for my solution edit!]
You can use the python built-in eval statement.
A word of caution though... you do not want to run eval() on a string that's coming into your program as external input provided by the user. That could create a security hole where users of your program could run arbitrary Python code of their own design.
In your example it'd look something like this:
tree = RegExTree()
expression = 'union(' + 'symbol(' + 'a' + ')' + ', ' + 'symbol(' + 'b' + ')' + ')'
tree.construct( eval(expression) ) # Notice the eval statement here

Categories

Resources