Checking if string inside quotes?

half.italian at gmail.com half.italian at gmail.com
Wed May 9 17:11:31 EDT 2007


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




More information about the Python-list mailing list