Mailing List Archive

How to remove "" from starting of a string if provided by the user
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
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
On 11Aug2020 00:05, Ganesh Pal <ganesh1pal@gmail.com> 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

Indeed. Using eval is extremely dangerous - it can execute _any_ python
code at all. Do not do that.

I would look for the quote character (you say " above but all your
examples actually use the ' character) at the start and end with
.startswith and .endswith methods, and cut out the middle with a slice
if they are both your target quote character (don't forget that Python
supports negative indices, making this pretty easy).

But I suspect that in the real world you'll find this approach
simplistic. Normally quotes introduce a special syntax between them,
such a \n to indicate a newline character and so forth, so _only_
stripping the quotes is not al that would be required.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
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
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
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 <python@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
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
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
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
On Tue, Aug 11, 2020 at 12:26 PM MRAB <python@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
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
> > On 2020-08-11 02:20, Ganesh Pal wrote:
> > > How do I check if it the value was (a) i.e string started and ended
> > > with a quote

Of course the original question was simple and there have been lots
of solutions given.

But I find this comes up periodically, and I'm always leery of using
something like line.replace("'", "").replace('"', '') because it
gets not only quote pairs, but things like "unmatched quotes'
or "it's a contraction".

I was thinking shlex had something like this, but it doesn't (it
can do the opposite, add quotation marks with appropriate escaping).
So I did a little playing around with re.sub.

At first I tried:
line = re.sub('"([^"]*)"', "\\1", line)
line = re.sub("'([^']*)'", "\\1", line)
which works for simple cases, but it can't detect apostrophes
properly, so it didn't work for one of my test strings,
"This one's apostrophe is in a more 'difficult' place."
(it sees the apostrophe as an open single quote, closes it
before difficult, leaving the one after difficult as an apostrophe).

Then I tried to use \b:
line = re.sub('\\b"([^"]*)"\\b', "\\1", line)
line = re.sub("\\b'([^']*)'\\b", "\\1", line)
but punctuation isn't considered part of a word, so it didn't work
right for strings like "some word."

I decided that really, the important thing was that the open quote
can't have an alphanumeric before it, and the end quote can't have
an alphanumeric after it:
line = re.sub('\W"([^"]*)"\W', "\\1", line)
line = re.sub("\W'([^']*)'\W", "\\1", line)
but no, that wasn't quite right since it didn't pick up quotes at
the beginning or end, and it loses some spaces too.

After some fiddling I ended up with
line = re.sub('(^|\W)"([^"]*)"(\W|$)', "\\1\\2\\3", line)
line = re.sub("(^|\W)'([^']*)'(\W|$)", "\\1\\2\\3", line)
which seems to work pretty well.

Any suggested improvements? I find this comes up now and then, so I'm
going to keep this around in my library for times when I need it,
and I'm sure there are cases I didn't think of. (And yes, I know
this is overkill for the original poster's question, but when I
need this I usually want something a little smarter.)

I've appended my test program below.

...Akkana

import re

s = '''Here are some strings.
"This string is quoted with double-quotes."
"Same, except this time the end quote is inside the period".
'This one is quoted with singles.'
"This has one of each and so shouldn't be changed.
"This has 'single quotes' inside double quotes, and it's got an apostrophe too."
"This one's apostrophe is in a more 'difficult' place."
'This has "double quotes" inside single quotes.'
'''

def remquotes(line):
"""Remove pairs of single and/or double quotes from the string passed in.
Try to preserve things that aren't quotes, like parentheses.
"""
line = re.sub('(^|\W)"([^"]*)"(\W|$)', "\\1\\2\\3", line)
line = re.sub("(^|\W)'([^']*)'(\W|$)", "\\1\\2\\3", line)

return line

if __name__ == '__main__':
for line in s.split('\n'):
print(remquotes(line))

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
On Tue, Aug 11, 2020, Ganesh Pal wrote:
>The possible value of stat['server2'] can be either (a)
>"'/fileno_100.txt'" or (b) '/fileno_100.txt' .

def stripquotes(s):
'''Strip leading single or double quotes to any depth'''
import re
pat = re.compile(r'^([\'"])(.*)(\1)$')
slast = None
while slast != s:
slast = s
s = pat.cub(r'\2', s)
return s
# end stripquotes(s)

Bill
--
INTERNET: bill@celestial.com Bill Campbell; Celestial Software LLC
URL: http://www2.celestial.com/ 6641 E. Mercer Way
Mobile: (206) 947-5591 PO Box 820
Fax: (206) 232-9186 Mercer Island, WA 98040-0820

Democracy is the theory that the common people know what they
want and deserve to get it good and hard. == H.L. Mencken
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
On 2020-08-11 20:43, Dennis Lee Bieber wrote:
> On Tue, 11 Aug 2020 14:17:39 -0400, Joel Goldstick
> <joel.goldstick@gmail.com> declaimed the following:
>
[snip]

> Warning -- it will fail if the input is just a pair of quotes or pair of
> apostrophes -- improvement is
>
>>>> while s and s[0] in ['"', "'"]:
> ... if s[0] == s[-1]:
> ... s = s[1:-1]
>
If the 'if' condition is False, then 's' will remain unchanged, and it
will loop forever.

I would suggest:

>>> while s[ : 1] in {'"', "'"} and s[ : 1] == s[-1 : ]:
... s = s[1 : -1]
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
On Tue, 11 Aug 2020, 02:20 Ganesh Pal, <ganesh1pal@gmail.com> 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()
>

BAFP

>
def maybe_unquote(string):
try:
return ast.literal_eval(string)
except ValueError:
return string
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user [ In reply to ]
12.08.20 18:53, MRAB ????:
> I would suggest:
>
>>>> while s[ : 1] in {'"', "'"} and s[ : 1] == s[-1 : ]:
> ...     s = s[1 : -1]

And the condition can be written as

s[ : 1] == s[-1 : ] in {'"', "'"}

or more efficiently as

s and s[0] == s[-1] in '\'"'

--
https://mail.python.org/mailman/listinfo/python-list