[英]Python find string enclosed in single quotes
在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
最简单的方法是检查它是否以引号开头和结尾:
if i.startswith("'") and i.endswith("'"):
print "found"
这当然不会告诉您任何其他信息,例如它是否包含匹配的引号,或者实际上包含的不只是单个引号字符。 如果那很重要,则添加一个检查字符串是否长于一个字符(如果希望在引号之间包含一些字符,则大于2):
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
码:
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的字符串,因为它们可能是单引号,假设这可能会给您的系统造成问题。
arr=["string","string'1" ,"'string2'"]
for each in arr:
if each[0] =="'" and each[-1] =="'":
print 'found'
print each
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.