How to remove "" from starting of a string if provided by the user

MRAB python at mrabarnett.plus.com
Tue Aug 11 12:24:50 EDT 2020


On 2020-08-11 02:20, Ganesh Pal wrote:
 > 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 ?
 >

I gave 2 possible solutions. Try the first one, which was to use the 
.strip method to remove the quotes.

The reason that startswith and endwith don't seem to work is that you're 
checking for the presence of " (double quote) characters, but, according 
to what you've posted, the strings contain ' (single quote) characters.

[snip]



More information about the Python-list mailing list