【问题标题】:Python: how to ignore 'substring not found' errorPython:如何忽略“未找到子字符串”错误
【发布时间】:2014-05-18 08:22:07
【问题描述】:

假设您有一个字符串数组 'x',其中包含很长的字符串,并且您想在数组 x 的每个字符串中搜索以下子字符串:“string.str”。

x绝大多数 元素中,有问题的子字符串将位于数组元素中。但是,也许一次或两次,它不会。如果不是,那么……

1) 有没有办法忽略大小写,然后使用if 语句移动到x 的下一个元素?

2) 如果您在x 的任何特定元素中寻找许多不同的子字符串,那么有没有一种方法可以在没有if 语句的情况下执行此操作,您可能最终会在其中编写大量的if 声明?

【问题讨论】:

  • 第二个问题 - 如果任何子字符串包含在 x 的元素中,您是否只感兴趣?还是您会根据 x 包含的子字符串以不同方式处理 x 中的元素?

标签: python string substring


【解决方案1】:

您需要 tryexcept 块。这是一个简化的例子:

a = 'hello'
try:
    print a[6:]
except:
    pass

扩展示例:

a = ['hello', 'hi', 'hey', 'nice']
for i in a:
    try:
        print i[3:]
    except:
        pass

lo
e

【讨论】:

  • 这会自动带你回到 for 循环的开头,忽略 try-except 块之后的任何内容吗?
  • @simply_helpful。什么意思?
  • 如果“except”被激活,程序运行的下一条语句是什么?
  • @simply_helpful,如果 except 被激活,它将只是 pass,然后它将继续执行这些块之后的其余代码。
  • @simply_helpful,提供扩展示例
【解决方案2】:

您可以使用list comprehension 简洁地过滤列表:

按长度过滤:

a_list = ["1234", "12345", "123456", "123"]
print [elem[3:] for elem in a_list if len(elem) > 3]
>>> ['4', '45', '456']

按子字符串过滤:

a_list = ["1234", "12345", "123456", "123"]
a_substring = "456"
print [elem for elem in a_list if a_substring in elem]
>>> ['123456']

通过多个子字符串过滤(通过比较filtered数组大小和子字符串的数量来检查是否所有子字符串都在元素中):

a_list = ["1234", "12345", "123456", "123", "56", "23"]
substrings = ["56","23"]
print [elem for elem in a_list if\
             len(filter(lambda x: x in elem, substrings)) == len(substrings)]
>>> ['123456']

【讨论】:

  • 我不得不说我认为你的命名约定真的很混乱。在实际使用该变量时使用_ 作为变量名并不是通常的使用方式。通常_ 用于无关紧要的变量(例如拆箱元组而只对第一个感兴趣:a, _ = tpl
  • 谢谢。将 _ 更改为 elem。
【解决方案3】:

好吧,如果我理解你写的内容,你可以使用continue 关键字跳转到数组中的下一个元素。

elements = ["Victor", "Victor123", "Abcdefgh", "123456", "1234"]
astring = "Victor"

for element in elements:
  if astring in element:
    # do stuff
  else:
   continue # this is useless, but do what you want, buy without it the code works fine too.

对不起我的英语。

【讨论】:

    【解决方案4】:

    使用any() 查看是否有任何子字符串在x 的项目中。 any() 将使用一个生成器表达式并且它表现出 短路 行为 - 它会返回 True 和第一个计算结果为 True 的表达式并停止 使用 生成器.

    >>> substrings = ['list', 'of', 'sub', 'strings']
    >>> x = ['list one', 'twofer', 'foo sub', 'two dollar pints', 'yard of hoppy poppy']
    >>> for item in x:
        if any(sub in item.split() for sub in substrings):
            print item
    
    
    list one
    foo sub
    yard of hoppy poppy
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 2015-01-05
      • 2021-12-18
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      相关资源
      最近更新 更多