Home > Mobile >  Python - How to check if my string contain any element in an array and get the repeated value?
Python - How to check if my string contain any element in an array and get the repeated value?

Time:11-15

for line in lines
if any(word in line for word in Array):
    print(word)

I am using something similar to this, but I am not able to print it out. For example:

String1 = " I am a newbie".
String2 = " Hello There".
Array = [newbie, hello, world]

I want to get the repeated word when I loop through each line. Thanks!!

String1 = " I am a newbie".
String2 = " Hello There".
Array = [newbie, hello, world]

loop 1: newbie loop 2: Hello

CodePudding user response:

I think there maybe a more efficient way but I managed to do it this way: (I assumed that hello word starts with small letter h so that the output is as you wrote

String1 = " I am a newbie"
String2 = " hello There"
Array = ["newbie", "hello", "world"]

for word in String1.split(" "):
    for word_array in Array:
        if word_array == word:
            print(word)
        else:
            pass
            
for word in String2.split(" "):
    for word_array in Array:
        if word_array == word:
            print(word)
        else:
            pass

CodePudding user response:

It can be done in the following way.

String1 = " I am a newbie"
String2 = " hello There"
Array = ["newbie", "hello", "world"]

for word in String1.split(" "):
    if word in Array:
        print("loop 1:", word)

for word in String2.split(" "):
    if word in Array:
        print("loop 2:", word)
  • Related