You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Python:使用filter获取指定字符串中字母的索引

获取字符串中字母的索引(使用filter函数)

Got it, let's work through this. You need to use Python's filter() function to grab the indices of all alphabetic characters in "Bob's tank has a big boom!" and store them in a list—right now you can collect the letters themselves, but not their positions.

Here's how to do it step by step:

First, define your string:

str_ = "Bob's tank has a big boom!"

The key trick here is pairing each character with its index first, since filter() operates on elements but we need position data. We can use enumerate() for this—it generates an iterator of tuples where each tuple is (index, character).

Then we'll use filter() to keep only the tuples where the character is an alphabet letter (via the isalpha() method), and finally extract the index from each filtered tuple to build our list.

Putting it all together:

# Pair indices with characters, filter for letters, then extract indices
letter_indices = list(map(lambda x: x[0], filter(lambda item: item[1].isalpha(), enumerate(str_))))

Let's break down each part:

  • enumerate(str_) creates pairs like (0, 'B'), (1, 'o'), (2, 'b'), (3, "'"), ...
  • The inner lambda item: item[1].isalpha() tells filter() to keep only tuples where the second element (the character) is an alphabet letter
  • map(lambda x: x[0], ...) takes each filtered tuple and pulls out the first element (the index)
  • Wrapping everything in list() converts the resulting iterator into a concrete list

If you run this, you'll get the following output:

print(letter_indices)
# Output: [0, 1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 15, 16, 17, 19, 20, 21]

Just a quick side note: A list comprehension might feel more readable for this task (like [i for i, char in enumerate(str_) if char.isalpha()]), but since you specifically asked to use filter(), the above solution fits your requirement perfectly.

内容的提问来源于stack exchange,提问作者user6510891

火山引擎 最新活动