简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM