简体   繁体   English

Python查找用单引号引起来的字符串

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

相关问题 用双引号或单引号引起来的正则表达式字符串 - regex string enclosed by double quote or single quotes 如何将字符串类型的“dd/mm/yyyy”格式化为python中单引号括起来的“yyyy-mm-dd”? - How to format “dd/mm/yyyy” of string type to “yyyy-mm-dd” enclosed in single quotes in python? 我如何在python regex中找到单引号内的字符串 - How can i find the string inside single quotes in python regex python 字符串格式化单引号和双引号 - python string formatting single quotes and double quotes Python通过单引号解析字符串 - Python Parseing String by Single Quotes 正则表达式匹配所有封闭''(2单引号) - Regular Expression to Match All Enclosed '' (2 Single Quotes) Python 正则表达式模式以查找包含在预处理器指令中的字符串 - Python regex pattern to find string enclosed in preprocessor directives 删除所有用引号引起来的内容或在Python中是数字吗? - Deleting everything that is enclosed with quotes or is a number in Python? 期望用双引号括起来的属性名称 - 使用Python将字符串转换为json对象 - Expecting property name enclosed in double quotes - converting a string to a json object using Python 如何将逗号分隔的字符串转换为用引号''括起来的每个单词到 python 中的列表? - How to convert a comma separated string with each word enclosed in quotes ' ' to a list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM