英文:
How can I get the index of a string in Python list, which contains a certain character?
问题
我已经使用line.split(":")
方法将多个字符串放入列表中,其中一个包含我想要找到并返回其在列表中的索引的特定字符。
例如:
s = "Hello StackOverflow!"
lst = s.split(" ") # ["Hello", "StackOverflow!"]
现在我想要获取字符'!'
的索引,所以期望的输出应该是索引1
,因为它在第二个字符串中。我无法使用lst.find('!')
来实现,因为它只适用于列表中的字符,而不适用于列表中的字符串。也许您可以帮助找到一个简单的解决方案。
英文:
I have put multiple strings in a list with the line.split(":")
method and one of them contains a certain character I want to find and return its index in the list.
For example:
s = "Hello StackOverflow!"
lst = s.split(" ") # ["Hello", "StackOverflow!"]
Now I want to get the index of character '!'
, so the desired output should be index 1
, as it's in the second string. I could not make it work with lst.find('!')
, as it works only for characters in list and not strings in lists. Probably you can help find a simple solution.
答案1
得分: 2
idx = next((i for i, word in enumerate(s.split()) if search_string in word), None)
要明确处理 StopIteration
,而不是默默地返回 None
,请从语句中删除第二个参数,并使用 try/except
块:
try:
idx = next(i for i, word in enumerate(s.split()) if search_string in word)
except StopIteration:
... # 进行一些操作
英文:
idx = next((i for i, word in enumerate(s.split()) if search_string in word), None)
To handle StopIteration
explicitly, instead of silently returning None
, remove the second parameter from the statement and use a try/except
block:
try:
idx = next(i for i, word in enumerate(s.split()) if search_string in word)
except StopIteration:
... # do something
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论