[英]Python find string enclosed in single quotes
In python how to find the string is enclosed within 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
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):
如果那很重要,则添加一个检查字符串是否长于一个字符(如果希望在引号之间包含一些字符,则大于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
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. 忽略长度为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.