user6510891
user6510891

Reputation:

Retrieve indices of letters in a string for python

I have a string: "Bob's tank has a big boom!"

I want to use filter to find the indices of where letters of the alphabet appear in the string to save their placement to a list.

import string
alphabet = string.ascii_lowercase

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

list_index = list(filter(lambda x: x in alphabet, str_))

Currently it just collects all the letters, but i'd like to know their index in the object str_.

Edit for more clarity

Output should be:

[0,1,2,4,6,7...]
[B,o,b,s,t,a...]

Upvotes: 1

Views: 100

Answers (2)

jpp
jpp

Reputation: 164843

This gives each permitted letter and respective position as a list of tuples:

import string

alphabet = string.ascii_lowercase
string = "Bob's tank has a big boom!"

[(j, i) for i, j in enumerate(string) if j in alphabet]

# [('o', 1), ('b', 2), ('s', 4), ('t', 6), ('a', 7), ('n', 8),
#  ('k', 9), ('h', 11), ('a', 12), ('s', 13), ('a', 15), ('b', 17),
#  ('i', 18), ('g', 19), ('b', 21), ('o', 22), ('o', 23), ('m', 24)]

Upvotes: 1

heemayl
heemayl

Reputation: 42137

List comprehension with enumerate:

[i for i, v in enumerate(str_) if v in alphabet]
  • i is the index, v is the value at corresponding index i, while enumerate-ing over the input string

  • if v in alphabet does the membership test; if found, the index is saved

Example:

In [58]: import string
    ...: alphabet = string.ascii_lowercase
    ...: 
    ...: str_ = "Bob's tank has a big boom!"
    ...: 

In [59]: [i for i, v in enumerate(str_) if v in alphabet]
Out[59]: [1, 2, 4, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 19, 21, 22, 23, 24]

Upvotes: 1

Related Questions