Ok so I have this string (for example):
var = "I eat breakfast."
What i would like to do is to check if that string contains "ea".
Ok so I have this string (for example):
var = "I eat breakfast."
What i would like to do is to check if that string contains "ea".
Use word in sentence
. For example:
>>> 'el' in 'Hello'
True
>>> 'xy' in 'Hello'
False
For your reference, check: python in
operator use cases
Simple:
>>> var = "I eat breakfast."
>>> 'ea' in var
True
I'm not clear what you mean by "put those values into a list." I assume you mean the words:
>>> [w for w in var.split() if 'ea' in w]
['eat', 'breakfast.']
This is a duplicate of Finding multiple occurrences of a string within a string in Python
You can use find(str, startIndex)
like so:
var = "I eat breakfast."
locations = []
index = 0
while index < len(var):
index = var.find('ea', index)
if index == -1:
break
locations.append(index)
index += 2
locations
is a list of the indices where 'ea'
was found.
You can use in
to check if a string contains a substring. It also sounds like you want to add var
to a list if it contains a substring. Observe the following interactive session:
In [1]: var = "I eat breakfast."
In [2]: lst = []
In [3]: if "ea" in var:
...: lst.append(var)
...:
In [4]: lst
Out[4]: ['I eat breakfast.']