Home > front end >  Python How to find a specific string from a list and print that line out?
Python How to find a specific string from a list and print that line out?

Time:10-20

I have a list and in that list, I am trying to find a specific string in that list by asking the user to enter in a word and I will print that word and the line that it is from

This is one list

list = ['An American', 'Barack Obama', '4.7', '18979']
['An Indian', 'Mahatma Gandhi', '4.7', '18979']
['A Canadian', 'Stephen Harper', '4.6', '19234']

For example, if I can input "ste" in the string and it should print the 3rd line as "Stephen Harper" is in there

I tried this but it did not work:

find_String = input("Enter a string you're looking for: ")
if find_String in list:
   print(list)
else:
   print("String not found!")

CodePudding user response:

arr = ['An American', 'Barack Obama', '4.7', '18979', 'An Indian', 'Mahatma Gandhi', '4.7', '18979',
    'A Canadian', 'Stephen Harper', '4.6', '19234']

inputStr = input("Enter String: ")

for val in arr:
    if inputStr in val:
        print(val);

This isn't null safe

This will also print all the values that have the specified substring, if you want only the first, add a break to the end of the if condition

CodePudding user response:

Well it doesn't work because of the following reasons :-

  1. variable list is only holding one list object, the first one, the rest 2 are not in the variable.
  2. It can't be accomplished with a simple if statement, for it has to iterate through the 3 lists within the list variable.

The following code will work :-

L1 = [['An American', 'Barack Obama', '4.7', '18979'],
['An Indian', 'Mahatma Gandhi', '4.7', '18979'],
['A Canadian', 'Stephen Harper', '4.6', '19234']]

find_String = input("Enter a string you're looking for: ")

for data in L1:
   for string in data:
      if find_String.lower() in string.lower():
         print(data)
         exit(0)
else:
   print("String not found!")
  • Related