你可以使用以下方法在Python列表中获取包含特定字符的字符串的索引:

huangapple go评论83阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年8月4日 03:52:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定