syko
syko

Reputation: 13

Using .find to search a string inside a list

I want to loop through a list of strings...

eg:

list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty']

I want to loop through the list items and search for the location of 'Hello!' within the string in each case an record its location.

Any ideas?

Upvotes: 1

Views: 7834

Answers (5)

Shruti Srivastava
Shruti Srivastava

Reputation: 398

in case you are searching for multiple items in a list say Hello and name

find = lambda searchList, elem: [[i for i, x in enumerate(searchList) if x == e] for e in elem] find(list_of_strings,['Hello','name'])

output is a list with the positions of the elements you are searching for in the order that you listed them

Upvotes: 1

Josh Smeaton
Josh Smeaton

Reputation: 48710

Use a list comprehension to collect the indexes of your wanted string:

>>> list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty', 'My Name is Josh']
>>> [s.find('Hello!') for s in list_of_strings]
[0, 0, 0, -1]

Note how the negative 1 shows that the final string does not contain the value you're looking for.

Upvotes: 2

user142650
user142650

Reputation:

You could try list comprehensions

[(s, s.lower().index('hello')) for s in list_of_strings if s.lower() == 'hello']

Upvotes: 2

slackmart
slackmart

Reputation: 4924

>>> list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty']

>>> indices = [position for position, phrase in enumerate(list_of_strings) if 'Hello!' in phrase]
>>> print indices
[0, 1, 2]

Using a comprehension list, loop over the list and check if the string has the Hello! string inside, if yes, append the position to the matches list.

Note: The enumerate build in brings you the index for each element in the list.

Upvotes: 1

Mauro Baraldi
Mauro Baraldi

Reputation: 6550

Use the string.find method.

>>> phrase = 'Hello, my name is Syko'
>>> phrase.find('Hello')
0

Upvotes: 2

Related Questions