Checking if string inside quotes?

Michael Yanowitz m.yanowitz at kearfott.com
Wed May 9 17:31:32 EDT 2007


Thanks, but it is a little more complicated than that,
  the string could be deep in quotes.

   The problem is in string substitution.
Suppose I have a dictionary with MY_IP : "172.18.51.33" 

  I need to replace all instances of MY_IP with "172.18.51.33"
in the file.
  It is easy in cases such as:
  if (MY_IP == "127.0.0.1"):

  But suppose I encounter:"
 ("(size==23) and (MY_IP==127.0.0.1)")
  
   In this case I do not want:
 ("(size==23) and ("172.18.51.33"==127.0.0.1)")
    but:
 ("(size==23) and (172.18.51.33==127.0.0.1)")
    without the internal quotes.
 How can I do this?
  I presumed that I would have to check to see if the string
was already in quotes and if so remove the quotes. But not
sure how to do that?
  Or is there an easier way?

Thanks in advance:
Michael Yanowitz

-----Original Message-----
From: python-list-bounces+m.yanowitz=kearfott.com at python.org
[mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf
Of half.italian at gmail.com
Sent: Wednesday, May 09, 2007 5:12 PM
To: python-list at python.org
Subject: Re: Checking if string inside quotes?


On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow... at kearfott.com> wrote:
> Hello:
>
>    If I have a long string (such as a Python file).
> I search for a sub-string in that string and find it.
> Is there a way to determine if that found sub-string is
> inside single-quotes or double-quotes or not inside any quotes?
> If so how?
>
> Thanks in advance:
> Michael Yanowitz

I think the .find() method returns the index of the found string.  You
could check one char before and then one char after the length of the
string to see.  I don't use regular expressions much, but I'm sure
that's a more elegant approach.

This will work. You'll get in index error if you find the string at
the very end of the file.

s = """
foo
"bar"
"""
findme = "foo"
index = s.find(findme)

if s[index-1] == "'" and s[index+len(findme)] == "'":
	print "single quoted"
elif s[index-1] == "\"" and s[index+len(findme)] == "\"":
   print "double quoted"
else:
   print "unquoted"

~Sean

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





More information about the Python-list mailing list