473,394 Members | 1,811 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Checking if string inside quotes?

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

May 9 '07 #1
4 12680
On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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

May 9 '07 #2
On May 9, 4:31 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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....@python.org

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

On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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
In "nearby" quotes or in quotes at all?
import re
a='abc"def"ghijk'
b=re.sub( r'([\'"])[^\1]*\1', '', a )
b.replace( 'ghi', 'the string' )
#fb: 'abcthe stringjk'
edit()

Here, you get the entire file -in b-, strings omitted entirely, so you
can't write it back.

I've used `tokenize' to parse a file, but you don't get precisely your
original back. Untokenize rearrages your spacings. Equivalent
semantically, so if you want to compile immedately afterwords, you're
alright with that. Short example:
from tokenize import *
import token
from StringIO import StringIO
a= StringIO( 'abc "defghi" ghi jk' )
from collections import deque
b= deque()
for g in generate_tokens( a.readline ):
if g[0]== token.NAME and g[1]== 'ghi':
b.append( ( token.STRING, '"uchoose"' ) )
else:
b.append( g )

untokenize( b )
#fb: 'abc "defghi""uchoose"jk '
edit()
acb

May 9 '07 #3
On May 9, 2:31 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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....@python.org

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

On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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
In that case I suppose you'd have to read the file line by line and if
you find your string in the line then search for the indexes of any
matching quotes. If you find matching quotes, see if your word lies
within any of the quote indexes.

#!/usr/bin/env python

file = open("file", 'r')
findme= "foo"
for j, line in enumerate(file):
found = line.find(findme)
if found != -1:
quotecount = line.count("'")
quoteindexes = []
start = 0
for i in xrange(quotecount):
i = line.find("'", start)
quoteindexes.append(i)
start = i+1

f = False
for i in xrange(len(quoteindexes)/2):
if findme in
line[quoteindexes.pop(0):quoteindexes.pop(0)]:
f = True
print "Found %s on line %s: Single-Quoted" % (findme, j
+1)
if not f:
print "Found %s on line %s: Not quoted" % (findme, j+1)
It's not pretty but it works.

~Sean

May 10 '07 #4
On May 9, 8:48 pm, half.ital...@gmail.com wrote:
On May 9, 2:31 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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....@python.org
[mailto:python-list-bounces+m.yanowitz=kearfott....@python.org]On Behalf
Of half.ital...@gmail.com
Sent: Wednesday, May 09, 2007 5:12 PM
To: python-l...@python.org
Subject: Re: Checking if string inside quotes?
On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kearfott.comwrote:
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

In that case I suppose you'd have to read the file line by line and if
you find your string in the line then search for the indexes of any
matching quotes. If you find matching quotes, see if your word lies
within any of the quote indexes.

#!/usr/bin/env python

file = open("file", 'r')
findme= "foo"
for j, line in enumerate(file):
found = line.find(findme)
if found != -1:
quotecount = line.count("'")
quoteindexes = []
start = 0
for i in xrange(quotecount):
i = line.find("'", start)
quoteindexes.append(i)
start = i+1

f = False
for i in xrange(len(quoteindexes)/2):
if findme in
line[quoteindexes.pop(0):quoteindexes.pop(0)]:
f = True
print "Found %s on line %s: Single-Quoted" % (findme, j
+1)
if not f:
print "Found %s on line %s: Not quoted" % (findme, j+1)

It's not pretty but it works.

~Sean
This approach omits double-quoted strings, escaped single-quotes "'a
\'b' my tag", triple-quoted strings, as well as multi-line strings of
any type.

Depends what constraints you can sacrifice. Maybe character-at-a-
time, or manually untokenize the solution above. For generic input,
use mine.

May 10 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Anders Dalvander | last post by:
os.popen does not work with parameters inside quotes, nor do os.popen. At least on Windows. import os cmd = '"c:\\command.exe" "parameter inside quotes"' os.popen4(cmd) Results in the...
7
by: RBohannon | last post by:
I'm using A2K. I'm inputing data from a text file into my DB, and I need to check for the data already existing in the DB. If it's already in the DB, I don't want to reenter it. The two...
1
by: Zlatko Matić | last post by:
I have a problem when working with PostrgeSQL as back-end. Namely, PostgreSQL syntax uses doble quotes for table names and field names. For example: select = from public."Customers" Therefore,...
5
by: Ann Marinas | last post by:
Happy New Year to all! :D I am currently developoing an application that imports data from a CSV file. Each comma represents an array item that I need to extract data with. My problem is...
12
by: Jeff S | last post by:
In a VB.NET code behind module, I build a string for a link that points to a JavaScript function. The two lines of code below show what is relevant. PopupLink = "javascript:PopUpWindow(" &...
11
by: jarod1701 | last post by:
Hi, i'm currently trying to replace an unknown string using regular expressions. For example I have: user_pref("network.proxy.http", "server1") What do I have to do to replace the...
9
by: a | last post by:
I need to write a regular expression to match a quoted string in which the double quote character itself is represented by 2 double quotes. For example: "beginning ""nested quoted string"" end"...
27
by: user | last post by:
Have require file with several query stings in it. Depending on user input one of strings is selected. Everything going along smoothly until I wanted to also input a variable in string. If I put...
3
by: rajmohan.h | last post by:
Hi all, Suppose I have a string which contains quotes inside quotes - single and double quotes interchangeably - s = "a1' b1 " c1' d1 ' c2" b2 'a2" I need to start at b1 and end at b2 - i.e. I...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.