[英]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.