0

I have a list of strings:

my_list = ["John 123", "Johnny 232", "Jane 344"]

What I want to do is check if a string in my_list does not contain a variable exactly, but anything else in the string after the variable doesn't matter.

For example if I have var = "John", my_list[0] would return True, but both my_list[1] and my_list[2] would return False. I need to check the entire list or until one returns True, whichever comes first.

EDIT: Here's a snippet of the actual code I'm working on:

names = []
rank, male, female = info
 for name in names:
  if male not in names:
   names.append(male + " " + rank + '\n')
  if female not in names:
   names.append(female + " " + rank + '\n')

info gets pulled from a html file, but for example will be something like ['123', 'John', 'Jane'], a number followed by a male name and a female name. My problem as of now is obviously the if statements will always be True, resulting in duplicate entries besides for the number.

2 Answers2

0

You can use the any() function for this, along with a list comprehension.

if any(var in item for item in my_list)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

You could do it with regular expressions easily. List comprehension

import re


my_list = ["John 123", "Johnny 232", "Jane 344"]

#Just an output list for you to see the True & False output
outputlist = []


for name in my_list:
    if re.search(r'\bJohn\b',name) != None:
        outputlist.append(True)
    else:
        outputlist.append(False)



'''
#List comprehension
outputlist = [True if re.search(r'\bJohn\b',name) != None else False for name in my_list]
'''

print(outputlist)

Output:

[True, False, False]
[Finished in 0.3s]
Ice Bear
  • 2,676
  • 1
  • 8
  • 24
  • This works perfectly, but how do I do the same with a variable instead of hard coding "John"? I'm lousy with regex haha – Ian Waddell Dec 14 '20 at 06:41
  • you mean a `variable`? containing a specific string? you can just change from the regex like this for example `re.search(r'\b'+variable+'\b',name)` – Ice Bear Dec 14 '20 at 06:43