The problem I am facing is that I need to find the position of a string
Code:
file = open('data.txt', 'r')
print file.read
data.txt contains
"banana", "mango", "apple", "pear", "dragon fruit"
For example how do I find the position of the string "mango"?
Advertisement
Answer
You can find the position of the word within the file using index. Try the following:
with open('data.txt', 'r') as f:
content = f.read()
print content.index('mango')
This would return the index of the word if it exists or give an error if it doesn’t find the word within the file.