You should use regex (with word boundary) as str.find returns the first occurrence. Then use the start attribute of the match object to get the starting index.
import re
string = 'This is laughing laugh'
a = re.search(r'\b(laugh)\b', string)
print(a.start())
>> 17
You can find more info on how it works here.
Answer from DeepSpace on Stack OverflowYou should use regex (with word boundary) as str.find returns the first occurrence. Then use the start attribute of the match object to get the starting index.
import re
string = 'This is laughing laugh'
a = re.search(r'\b(laugh)\b', string)
print(a.start())
>> 17
You can find more info on how it works here.
try this:
word = 'laugh'
string = 'This is laughing laugh'.split(" ")
index = string.index(word)
This makes a list containing all the words and then searches for the relevant word. Then I guess you could add all of the lengths of the elements in the list less than index and find your index that way
position = 0
for i,word in enumerate(string):
position += (1 + len(word))
if i>=index:
break
print position
Hope this helps.
Videos
As i've already mentioned - the problem is in your list to string conversion.
When you call str() on pytz.all_timezones - you get string representation of list, including all punctuation characters. So, when you call split - each word ( except first one ) in resulting list starts with ' character.
Try iterating pytz.all_timezones directly like this snippet:
for index, zone in enumerate(pytz.all_timezones):
if zone.lower().startswith(word):
print(index)
Maybe you can use
import pytz
word = 'iran'
text = [x.lower() for x in pytz.all_timezones]
for t in text:
if t.startswith(word):
print(text.index(t))
List comprehension and lower() is used to make a list the elements of which are strings.
These elements are checked with startswith() and if its return value is True, its index is printed with index().
Output:
507
Fixed it:
def findword(string, word):
import re
strings=string.split()
if word in strings:
matches = re.finditer(word ,string) #reversed (string, word), check documentation for correct usage
matches_positions = [match.start() for match in matches]
print(matches_positions)
else:
print("Word not found")
string=" how are you doing how do you you"
word= "you"
findword(string, word)
On line 5, I reversed (string, word). Please check the documentation for correct usage.
re.finditer(pattern, string, flags=0) takes the 1st parameter as pattern and second as string:
def findword(string, word):
import re
strings = string.split()
if word in strings:
matches = re.finditer(word, string) # see the change here
matches_positions = [match.start() for match in matches]
print(matches_positions)
else:
print("Word not found")
string=" how are you doing how do you you"
word= "you"
findword(string, word)
Output:
[9, 26, 30]