Python:如何忽略“未找到子字符串”错误
假设你有一个字符串数组'x
',里面包含了很长的字符串,你想在每个字符串中查找一个子字符串:"string.str"。
在这个数组x
的大部分元素中,你要找的子字符串都会存在。但是,也许有一两次,它可能不存在。如果不存在的话……
1) 有没有办法可以忽略大小写,然后直接跳到x
的下一个元素,使用一个if
语句来实现?
2) 有没有办法在不使用if
语句的情况下进行查找,特别是当你要找的子字符串有很多种,而你可能会写出很多if
语句的时候?
4 个回答
0
使用 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
>>>
0
好的,如果我理解你写的内容没错的话,你可以使用 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.
抱歉我的英语不好。
1
你可以使用列表推导式来简洁地过滤列表:
按长度过滤:
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']
按多个子字符串过滤(通过比较过滤后的数组大小和子字符串的数量,来检查所有子字符串是否都在元素中):
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']
3
你需要使用 try
和 except
这两个部分。下面是一个简单的例子:
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