在python中如何找到字符串用单引号括起来
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
答案 0 :(得分:5)
最简单的方法是检查它是否以引号开头和结尾:
if i.startswith("'") and i.endswith("'"):
print "found"
这当然不会告诉你任何其他内容,例如它是否包含匹配的引号,或者确实包含的不仅仅是单引号字符。如果这很重要,那么添加一个检查表明字符串长于一个字符(如果你希望它在引号之间包含某些内容,则大于2):
if i.startswith("'") and i.endswith("'") and len(i) > 1:
print "found"
答案 1 :(得分:1)
arr=["string","string'1" ,"'string2'"]
for item in arr:
if len(item) > 1 and item[0] == item[-1] == "'":
print "found", item
答案 2 :(得分:0)
<强>代码:强>
arr=["'","''","'''","'item","'item'","i'tem'"]
for i in arr:
if(len(i) > 1):
if i.startswith("'") and i.endswith("'"):
print("found")
print(i)
<强>输出:强>
found
''
found
'''
found
'item'
如果第一个和最后一个字母相等且等于'
,则字符串以引号开头和结尾。忽略长度为1的字符串,因为它们可能是单引号,假设这可能会导致系统出现问题。
答案 3 :(得分:-1)
arr=["string","string'1" ,"'string2'"]
for each in arr:
if each[0] =="'" and each[-1] =="'":
print 'found'
print each