The possible value of stat['server2'] can be either (a) "'/fileno_100.txt'" or (b) '/fileno_100.txt' .
How do I check if it the value was (a) i.e string started and ended with a quote , so that I can use ast.literal_eval() >>> import ast >>> stat = {} >>> stat['server2'] = "'/fileno_100.txt'" >>> stat['server2'] = ast.literal_eval(stat['server2']) >>> print stat['server2'] /fileno_100.txt >>> >>> if stat['server2'].startswith("\"") and stat['server2'].endswith("\""): ... stat['server2'] = ast.literal_eval(stat['server2']) ... >>> I tried startswith() and endswith(), doesn't seem to work ?. Is there a simpler way ? Regards, Ganesh On Tue, Aug 11, 2020 at 4:06 AM MRAB <pyt...@mrabarnett.plus.com> wrote: > On 2020-08-10 19:35, Ganesh Pal wrote: > > How to remove " from the starting and ending of a string , before > > comparison . Here is an example and my solution wtih eval ( I am advised > > not to use this one) , please suggest an alternative . I am on linux and > > python 2.7 > > > > g1@X1:/tmp$ cat file2.py > > #!/usr/bin/python > > > > # Case 1 - server2 file is "'/fileno_100.txt'" > > stat={} > > stat['server1'] = '/fileno_100.txt' > > stat['server2'] = "'/fileno_100.txt'" > > > > if stat['server1'] == eval(stat['server2']): > > print "OK" > > > > # Case 2 - server2 file is '/fileno_100.txt' > > stat['server2'] = "'/fileno_100.txt'" > > > > if stat['server1'] == eval(stat['server2']): > > print "OK" > > > > > > # Case 3 - server2 file can be in (a) '/fileno_100.txt' or (b) : > > "'/fileno_100.txt'" format > > > > g1@X1:/tmp$ python file2.py > > OK > > OK > > > You could strip off the quotes with the .strip method or use > literal_eval from the ast module. > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list