Rajeev
Rajeev

Reputation: 46949

Python find string enclosed in single quotes

In python how to find the string is enclosed within single quotes

  arr=["string","string'1" ,"'string2'"]

   for i in arr:
      if i //string enclosed in single quotes condition
            print "found"
            print i //which sould print only string2 in this case

Upvotes: 1

Views: 17036

Answers (4)

Duncan
Duncan

Reputation: 95722

Simplest way would be to check whether it both starts and ends with a quote:

if i.startswith("'") and i.endswith("'"):
    print "found"

That won't of course tell you anything else such as whether it contains matched quotes or indeed contains more than just a single quote character. If that matters then add in a check that the string is longer than one character (or greater than 2 if you want it to contain something between the quotes):

if i.startswith("'") and i.endswith("'") and len(i) > 1:
    print "found"

Upvotes: 8

mbdavis
mbdavis

Reputation: 4020

Code:

arr=["'","''","'''","'item","'item'","i'tem'"]
for i in arr:
    if(len(i) > 1):
        if i.startswith("'") and i.endswith("'"):
            print("found")
            print(i)

Output:

found
''
found
'''
found
'item'

if the first and last letters are equal and equal to ', then the string starts and ends with quotes. Ignoring strings of length 1 as they could be a single quote, assuming this could cause a problem for your system.

Upvotes: 0

perreal
perreal

Reputation: 98088

arr=["string","string'1" ,"'string2'"]
for item in arr:
    if len(item) > 1 and item[0] == item[-1] == "'":
        print "found", item

Upvotes: 1

MONTYHS
MONTYHS

Reputation: 924

arr=["string","string'1" ,"'string2'"]
for each in arr:
  if each[0] =="'" and each[-1] =="'":
     print 'found'
     print each

Upvotes: -1

Related Questions