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

Joel Goldstick joel.goldstick at gmail.com
Tue Aug 11 14:17:39 EDT 2020


On Tue, Aug 11, 2020 at 12:26 PM MRAB <python at mrabarnett.plus.com> wrote:
>
> 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]
>
> --
> https://mail.python.org/mailman/listinfo/python-list

I'm assuming that you don't want the string to start with single
quote, doublequote, or the other way around.  If you have that
situation, strip the first and last characters:

>>> s = "'Starts with double quote'"
>>> s1 = '"Starts with single quote"'
>>> if s[:1] == "'" or s[:1] == '"':
...   s_stripped = s[1:-1]
...
>>> s_stripped
'Starts with double quote'
>>> if s1[:1] == "'" or s1[:1] == '"':
...   s_stripped = s1[1:-1]
...
>>> s_stripped
'Starts with single quote'
>>>

This assumes the quotes match at both ends of the string
-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays


More information about the Python-list mailing list