+ 1

Find a word in a string

How do we find a word in a given string as below: teststring = ["https://www.Australia.com/go/", "london", "USA"] If I want to find word "Australia" in teststring using "in" keyword. it gives False. How do we do it then?

6th May 2019, 6:35 AM
Charchika
3 Réponses
+ 2
The problem is that your teststring variable is a list with three (string) elements. When you say "Australia" in teststring it checks to see if the string "Australia" is one of the elements in the list, not whether any of those elements contains that substring. So teststring = "https://www.Australia.com/go/" print("Australia" in teststring) #this would return True. Does that make sense?
6th May 2019, 10:18 AM
Russ
Russ - avatar
+ 1
Something like that ? : -------------------- teststring = ["https://www.Australia.com/go/", "london", "USA", ".Australia."] substring = 'Australia' result = [i for i in teststring if substring in i] print ("The string found in : " + str(result))
6th May 2019, 6:51 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 1
what you need to do is use regular expressions. Since you want to find a pattern match 'Australia' in the strings in your list. So iterate through your list and using the search function of the re package. Here is a basic example of a search import re string = 'This is a string that I want to search' x = re.search('that') print(x)
9th May 2019, 7:31 PM
Brian Petry
Brian Petry - avatar